映射对象更改对象数组

时间:2016-08-29 15:22:16

标签: 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'代码被选中......

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

2 个答案:

答案 0 :(得分:3)

您可以使用Object.assign()来"复制"在这种情况下的对象。然后只需映射requirements



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);




答案 1 :(得分:0)

您可以简单地循环并执行此操作

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 ={};
var innerArray = [];
for(var key in source) {
  if (source.hasOwnProperty(key)) {
    if(typeof source[key] === 'string') {
       target[key] = source[key];   
    } else {
      for(var i = 0; i < source[key].length; i++) {
        var temp = {};
        temp.acode = source[key][i].a.code;
        temp.bcode = source[key][i].b.code;
        innerArray.push(temp);
      }
      target[key] = innerArray;    
    }
  }
}

console.log(target);

这是小提琴 https://jsfiddle.net/Refatrafi/Lgryf2kv/12/