迭代数组中的对象并更改对象中的值

时间:2017-02-27 15:16:39

标签: javascript angularjs arrays javascript-objects

My Array如下

var values = [
{"firstname":"A","middlename":"B","lastname":"C"},
{"firstname":"L","middlename":"M","lastname":"N"},
{"firstname":"X","middlename":"Y","lastname":"Z"}
];

我想更改所有键的值 - 此数组中的firstname,middlename和lastname。

var newValues = [];
angular.forEach(values, function(item, key) {
    changedValues = {};
    angular.forEach(item, function(value, key1) {
          var changedValue = value + "constant";
          changedValues[key1] = changedValue 
    });
    newValues .push(changedValues )    
});

对此有任何帮助表示赞赏。在此先感谢。

4 个答案:

答案 0 :(得分:2)



var values = [{
    "firstname": "A",
    "middlename": "B",
    "lastname": "C"
  },
  {
    "firstname": "L",
    "middlename": "M",
    "lastname": "N"
  },
  {
    "firstname": "X",
    "middlename": "Y",
    "lastname": "Z"
  }
];
console.log(values.map(o => {
  return Object.keys(o).map(n => o[n] += "constant")
}));




答案 1 :(得分:0)

我认为你想要实现的是地图

你可以这样做:

var values = [
{"firstname":"A","middlename":"B","lastname":"C"},
{"firstname":"L","middlename":"M","lastname":"N"},
{"firstname":"X","middlename":"Y","lastname":"Z"}
];

var newArray = value.map(function(item) {
  return {
     "firstname" : item.firstname  + "constant",
     "middlename": item.middlename + "constant",
     "lastname"  : item.lastname   + "constant"
  }
})

答案 2 :(得分:0)

您可以使用map()reduce()并返回新的对象数组。



var values = [
  {"firstname":"A","middlename":"B","lastname":"C"},
  {"firstname":"L","middlename":"M","lastname":"N"},
  {"firstname":"X","middlename":"Y","lastname":"Z"}
]

var newValues = values.map(function(e) {
  return Object.keys(e).reduce(function(r, k) {
    return r[k] = e[k] + 'constant', r
  }, {})
})

console.log(newValues)




答案 3 :(得分:0)

映射对象,然后更改每个条目的值:

var values = [{
    "firstname": "A",
    "middlename": "B",
    "lastname": "C"
  },
  {
    "firstname": "L",
    "middlename": "M",
    "lastname": "N"
  },
  {
    "firstname": "X",
    "middlename": "Y",
    "lastname": "Z"
  }
];

let newValues = values.map(v => {
  let obj = {};
  for (let k in v) {
    if (v.hasOwnProperty(k))
      obj[k] = v[k] + "constant";
  }
  return obj;
});

console.log(newValues);