gpt4 book ai didi

javascript - 映射对象更改对象数组

转载 作者:行者123 更新时间:2023-11-28 18:25:42 26 4
gpt4 key购买 nike

在 Angular 应用程序中,我有以下具有一系列要求的对象:

var source = {
position: "xyz",
requirements: [
{ a: { code: "a1", name: "a1" }, b: { code: "b1", name: "b1" } },
{ a: { code: "a2", name: "a2" }, b: { code: "b2", name: "b2" } }
]
};

我需要创建该对象的副本,如下所示:

var target = {
position: "xyz",
requirements: [
{ acode: "a1", bcode: "b1" },
{ acode: "a2", bcode: "b2" }
]
};

因此仅选择“a”代码和“b”代码...

映射此类对象的最佳方法是什么?

最佳答案

您可以使用Object.assign()在这种情况下“复制”对象。然后只需映射需求即可。

var source = {
position: "xyz",
requirements: [
{ a: { code: "a1", name: "a1" }, b: { code: "b1", name: "b1" } },
{ a: { code: "a2", name: "a2" }, b: { code: "b2", name: "b2" } }
]
};

var copy = Object.assign({}, source);
copy.requirements = copy.requirements.map(item => {
return {acode: item.a.code, bcode: item.b.code}
});

console.log(source);
console.log(copy);

关于javascript - 映射对象更改对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39209775/

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