我有一个对象数组:
chachters = [{name: "Frodo", race: "hobitt", age: 111},
{name: "Gandalf", race: "human", age: 2019}],
{name: "Aragorn", race: "elf", age: 40}];
和一串字符串。
swords = ["Sting","Glamdring","Anduril"];
我想在“字符”中为对象添加键值对,以便将正确的剑分配给正确的字符。索引匹配,因为剑[0]需要添加到charachrers [0]中的值:
这就是我想要的角色:
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"}];
请帮忙。中土的成功取决于它。
答案 0 :(得分:3)
您可以使用map
和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);

答案 1 :(得分:3)
您可以将array#map
与spread syntax
一起使用。根据索引为角色添加一把剑。
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);
答案 2 :(得分:2)
使用#array.forEach并为数组的每个对象添加额外的键和swords数组中的值。
工作片段(这样,它将直接在原始数组中进行更改):
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);

如果chachters
是状态数组并且您正在更新状态,则使用以下方式:
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);

答案 3 :(得分:1)
您可以创建一个函数来将字符串数组附加到对象数组中;
例如:
此函数将用于将字符串数组附加到对象数组
function appendObjTo(swords, chachters ) {
return Object.freeze(swords.concat(chachters ));
}
根据您的定义:
swords = ["Sting","Glamdring","Anduril"];
const chachters = [{name: "Frodo", race: "hobitt", age: 111},
{name: "Gandalf", race: "human", age: 2019},
{name: "Aragorn", race: "elf", age: 40}];
const newChachters = appendObjTo(swords, chachters);
答案 4 :(得分:1)
请允许我试试。我不太熟悉.map():P
t
结果:
var characters = [
{name: "Frodo", race: "hobitt", age: 111},
{name: "Gandalf", race: "human", age: 2019},
{name: "Aragorn", race: "elf", age: 40}
];
var swords = ["Sting", "Glamdring", "Anduril"];
var charactersWithSwords = characters.map(function (character, index) {
character.swords = swords[index];
return character;
});
console.log(charactersWithSwords);