如何编辑数组的值

时间:2018-02-23 01:39:28

标签: javascript

我有一个例子:

var A = [{
  key: "iphone",
  value: "American"
}, {
  key: "sony",
  value: "Japan"
}]

我想做这个动作:

B=[{value:"American"},{value:"Japan"}]

我该怎么做?帮助我。

3 个答案:

答案 0 :(得分:2)

使用 Array.map 并返回带有值字段的新对象

<强>样本

var A =[{key:"iphone",value:"American"},{key:"sony",value:"Japan"}] ;

var result = A.map(d => ({ value: d.value }));
console.log(result);

答案 1 :(得分:1)

var B = A.map(function(obj) { return { value: obj.value }; });

var B = A.map(obj => ({ value: obj.value }));

答案 2 :(得分:0)

也许您更喜欢这种更具可读性的语法?

function myObjectConverter (inputObject) {
  var outputObject = {};
  // ignore the key property
  outputObject.Country1 = inputObject.value1;
  outputObject.Country2 = inputObject.value2;
  outputObject.Country3 = inputObject.value3;
  outputObject.Country4 = inputObject.value4;
  // transfer any other items with new names
  return outputObject;
}

var B = A.map(myObjectConverter);