Q:

Adding key value pair (value from an array) to specific objects in an array

I have an array of objects:
chachters = [{name: "Frodo", race: "hobitt", age: 111}, 
             {name: "Gandalf", race: "human", age: 2019}],
             {name: "Aragorn", race: "elf", age: 40}];

and an array of strings.
swords = ["Sting","Glamdring","Anduril"];

I want to add a key-value pair to the objects in 'characters' so the correct sword is assigned to the correct character. The indexes match in that swords[0] needs to be added to the value in charachrers[0]:
Here's what I'd like characters to look like:
 chachters =[{name:"Frodo", race:"hobitt", age:111,sword:"Sting"}, 
             {name:"Gandalf",race:"human",age:2019,sword:"Glamdring"}],
             {name:"Aragorn",race:"elf",age:40,sword:"Anduril"}];

Please help. The fait of middle earth depends on it.

A:

You can use map and Object.assign:

var chachters = [{name: "Frodo", race: "hobitt", age: 111}, 
             {name: "Gandalf", race: "human", age: 2019},
             {name: "Aragorn", race: "elf", age: 40}],
    swords = ["Sting","Glamdring","Anduril"];

var result = chachters.map( (obj, i) => Object.assign({ sword: swords[i] }, obj) );
console.log(result);

A:

You can use array#map with spread syntax. Add a sword to a character based on the index.

const chachters = [{name: "Frodo", race: "hobitt", age: 111}, {name: "Gandalf", race: "human", age: 2019},       {name: "Aragorn", race: "elf", age: 40}],
      swords = ["Sting","Glamdring","Anduril"],
      result = chachters.map((o,i) => ({...o, sword: swords[i]}));
console.log(result);

A:

Use #array.forEach and for each object of array add extra key with the value from swords array.
Working snippet (This way, it will do the changes directly in the original array):

let chachters = [
      {name: "Frodo", race: "hobitt", age: 111}, 
      {name: "Gandalf", race: "human", age: 2019},
      {name: "Aragorn", race: "elf", age: 40}];

let swords = ["Sting","Glamdring","Anduril"];

chachters.forEach((el,i) => {
     el.sword = swords[i];
})

console.log('chachters = ', chachters);

If chachters is a state array and you are updating the state then use this way:

let chachters = [
      {name: "Frodo", race: "hobitt", age: 111}, 
      {name: "Gandalf", race: "human", age: 2019},
      {name: "Aragorn", race: "elf", age: 40}];

let swords = ["Sting","Glamdring","Anduril"];

let newchachters = chachters.map((el,i) => ({...el, sword: swords[i]}))

console.log('chachters = ', chachters);
console.log('newchachters = ', newchachters);

