gpt4 book ai didi

javascript - 将键值对(数组中的值)添加到数组中的特定对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:47 26 4
gpt4 key购买 nike

我有一个对象数组:

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

和一个字符串数组。

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

我想向“字符”中的对象添加一个键值对,以便将正确的剑分配给正确的字符。需要将 swords[0] 中的索引匹配添加到 charachrers[0] 中的值:

这是我希望 Angular 色看起来像的样子:

 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"}];

请帮忙。中土世界的命运取决于它。

最佳答案

您可以使用mapObject.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);

关于javascript - 将键值对(数组中的值)添加到数组中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48961220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com