根据另一个对象的值在对象中创建新属性

时间:2018-03-23 14:45:36

标签: javascript arrays object

对于像这样的对象数组:

myArray = [
            {id: "1", type: "xxx"},
            {id: "2", type: "abc"},
            {id: "3", type: "xxx"},
            {id: "4", type: "yyy"}
];

如果需要为受type值影响的每个对象创建另一个属性,例如:

如果type === xxxnewProp = prop1

如果type === abcnewProp = prop2

如果type === yyynewProp = prop3

结果数组应如下所示:

myArray = [
            {id: "1", type: "xxx", newProp: "prop1"},
            {id: "2", type: "abc", newProp: "prop2"},
            {id: "3", type: "xxx", newProp: "prop1"},
            {id: "4", type: "yyy", newProp: "prop3"}
];

我用for循环和很多if语句做了,但可能有一个我不知道的更有效的解决方案。

有什么想法吗?

7 个答案:

答案 0 :(得分:4)

您可以使用所需的类型值来获取对象。



var myArray = [{ id: "1", type: "xxx" }, { id: "2", type: "abc" }, { id: "3", type: "xxx" }, { id: "4", type: "yyy" }];

myArray.forEach(o => o.newProp = { xxx: 'prop1', abc: 'prop2', yyy: 'prop3' }[o.type]);

console.log(myArray);




答案 1 :(得分:3)

使用包含其中一个类型时要添加的值的地图。然后,您可以在数组上@BodyParser.Of(BodyParser.Json.class)并返回一个新对象,其中添加了适当的值map

newProp

答案 2 :(得分:2)

如果您正在寻找功能性的js-one-liner,请点击这里:

// type2Prop is a object lookup table for type to newProp values
myArray.map(e => (v => v && (e.newProp = v))(type2Prop[e.type]))

注意:它还处理这种情况,如果type与已知类型中的任何内容不匹配,则不会添加属性。

答案 3 :(得分:1)

使用map

let myArray = [{id: "1", type: "xxx"},{id: "2", type: "abc"},{id: "3", type: "xxx"},{id: "4", type: "yyy"}];
        
let resp = myArray.map(x => {
  if(x.type === 'xxx') x.newProp = 'prop1';
  if(x.type === 'abc') x.newProp = 'prop2';
  if(x.type === 'yyy') x.newProp = 'prop3';
  return x;
 })
    
console.log(resp);

答案 4 :(得分:1)

您可以这样做,并在需要时添加其他类型:



const myArray = [
  {id: "1", type: "xxx"},
  {id: "2", type: "abc"},
  {id: "3", type: "xxx"},
  {id: "4", type: "yyy"}
];
const types = {
  "xxx": "prop1",
  "abc": "prop2",
  "yyy": "prop3",
};
const newArray = myArray.map(e=>{
  return {...e, newProp: types[e.type]};
});
console.log(newArray);




答案 5 :(得分:1)

  for(const el of myArray)
   el.newProp = {"xxx" : "prop1", "abc": "prop2" /*...*/ }[el.type];

答案 6 :(得分:1)

使用数组' map()

尝试以下操作



var myArray = [
            {id: "1", type: "xxx"},
            {id: "2", type: "abc"},
            {id: "3", type: "xxx"},
            {id: "4", type: "yyy"}
];

myArray = myArray.map(function(i){
  if(i.type==='xxx') i.newProp='prop1'
  else if(i.type==='abc') i.newProp='prop2'
  else if(i.type==='yyy') i.newProp='prop3'
  return i;
});
console.log(myArray);