JavaScript数组映射,同时将原始元素保留在数组中

时间:2019-06-22 04:04:32

标签: javascript arrays object ecmascript-6

我有这个数组。

const data = [
  { name: "A", age: "12" },
  { name: "B", age: "5" },
  { name: "C", age: "6" }
];

我想像这样向此数组添加名为key的其他属性。

const data = [
  { name: "A", age: "12", key: "A12" },
  { name: "B", age: "5", key: "B5" },
  { name: "C", age: "6", key: "C6" }
];

我对地图功能感到厌倦,输出不是我期望的。如何使用JS映射功能实现此目标。

const data = [
  { name: "A", age: "12"},
  { name: "B", age: "5"},
  { name: "C", age: "6"}
];

console.log(
  "MAP",
  data.map(element => (element.key = element.name + element.age))
);

3 个答案:

答案 0 :(得分:4)

您需要从map回调中返回一个对象:

const data = [
  { name: "A", age: "12"},
  { name: "B", age: "5"},
  { name: "C", age: "6"}
];

console.log(
  data.map(({ name, age }) => ({ name, age, key: name + age }))
);

如果您希望更改现有对象,请使用forEach代替.map

const data = [
  { name: "A", age: "12"},
  { name: "B", age: "5"},
  { name: "C", age: "6"}
];

data.forEach((obj) => {
  obj.key = obj.name + obj.age;
});
console.log(data);

答案 1 :(得分:3)

也使用逗号运算符返回element

const data = [
  { name: "A", age: "12"},
  { name: "B", age: "5"},
  { name: "C", age: "6"}
];

console.log(data.map(element => (element.key = element.name + element.age, element)));
.as-console-wrapper { max-height: 100% !important; top: auto; }

或者只需更改您的map回调以简化解构即可:

const data = [
  { name: "A", age: "12"},
  { name: "B", age: "5"},
  { name: "C", age: "6"}
];

console.log(data.map(({ name, age }) => ({ name, age, key: name + age})));
.as-console-wrapper { max-height: 100% !important; top: auto; }

答案 2 :(得分:1)

执行此操作的方法不止一种,Array.map是迄今提供的最简洁,最简洁的方法。以下是一些其他方法:

 const data = [ { name: "A", age: "12" }, { name: "B", age: "5" }, { name: "C", age: "6" } ];

let from = Array.from(data, ({name, age}) => ({name, age, key: name+age}))
let assign = data.map(({name, age}) => Object.assign({name, age}, {key: name+age}))

console.log('from: ', from)
console.log('assign: ', assign)

如果您想从所有values(假设全部是基元)生成密钥,您还可以执行以下操作:

const data = [
  { name: "A", age: "12", city: 'Miami' },  // "key": "A12Miami"
  { name: "B", age: "2", gender: 'M'},      // "key": "B2M"
];

let all = data.map(obj => 
  ({...obj, ...Object.fromEntries([['key', Object.values(obj).join('')]])}))

console.log(all)

这样,您不必指定或关心流行名称等。