我有一个对象列表
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" )
答案 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)
您可以使用map和object 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)