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

标签 javascript angularjs

在 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/

相关文章:

javascript - 模态中的模态或模态 Angular js 1 和 html 中的 div 到 "hide and show"

javascript - 使 form-in-a-div 出现在内容之上

php - 第一次尝试无法登录

javascript - Angular : accessing a JSON value using a variable key

angularjs - 状态激活时显示 2 个图像

Angularjs 在嵌套标签中进行翻译

angularjs - 如何在 AngularJS 中将对象添加到嵌套数组中?

javascript - Knockout js 订阅函数(对于可观察对象)正在 ko.applyBindings(...) 中执行

javascript - 获取下拉列表中选定的值

javascript - cordova inappbrowser 引用元素