JS-在其中一个对象上添加新的属性和值

时间:2019-04-03 17:02:43

标签: javascript arrays object

我有一个对象列表

const array = [
    {club: "Club A", number: 12},
    {club: "Club B", number: 12}
]

我想在其中一个对象中添加新属性

member: ["a", "b"]

应该是

const newArray = [
    {club: "Club A", number: 12, member: ["a", "b"]},
    {club: "Club B", number: 12}
]

尝试过地图

const newArray = array.map(obj => check if obj.club ==="Club A" )

4 个答案:

答案 0 :(得分:1)

您可以只分配新属性。

经典作业:

const
    array = [{ club: "Club A", number: 12 }, { club: "Club B", number: 12 }],
    member = ["a", "b"];
    
array.find(({ club }) => club === "Club A").member = member;

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或者采取Object.assign

const
    array = [{ club: "Club A", number: 12 }, { club: "Club B", number: 12 }],
    member = ["a", "b"];
    
Object.assign(array.find(({ club }) => club === "Club A"), { member });

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以使用mapobject destrcturing

const array = [{club: "Club A", number: 12},{club: "Club B", number: 12}]
let member = ["a", "b"]

const newArray = array.map(obj => obj.club === "Club A" ? {...obj,member} : obj)

console.log(newArray)

答案 2 :(得分:0)

您可以在地图中使用Object.assign

const array = [
    {club: "Club A", number: 12},
    {club: "Club B", number: 12}
]

const member = {member: ["a", "b"]};

const newArray = array.map(obj => obj.club === 'Club A' ? Object.assign(obj, member) : obj);
console.log(newArray);

答案 3 :(得分:0)

您可以使用find()来获取要编辑的项目。然后只需为其分配属性:

mapOrientation