根据条件在JavaScript中向数组添加额外的对象键

5

我的数组:

[
  {
    name: 'test1',
    state: 'OK',
    status: true,
    pending: 33,
    approved: 0,
    active: 0,
    inactive: 33
  },
  {
    name: 'test3',
    state: 'OK',
    status: true,
    pending: 33,
    approved: 0,
    active: 0,
    inactive: 33
  },
  {
    name: 'test4',
    state: 'OK',
    status: true
  }
]

如果对象中不存在“pending”,“approved”,“active”和“inactive”键,则需要输出以下内容:
期望输出:
[
  {
    name: 'test1',
    state: 'OK',
    status: true,
    pending: 33,
    approved: 0,
    active: 0,
    inactive: 33
  },
  {
    name: 'test3',
    state: 'OK',
    status: true,
    pending: 33,
    approved: 0,
    active: 0,
    inactive: 33
  },
  {
    name: 'test4',
    state: 'OK',
    status: true,
    pending: 0,
    approved: 0,
    active: 0,
    inactive: 0
  }
]

如何完成这个任务?

我尝试使用map,但是不知道如何设置条件。

我想将所有的值都设为零。


请问您能否在问题中包含您的尝试?谢谢。 - NewToJS
好的,请稍等…… - Mohamed Sameer
http://jsbin.com/yimebifoci/edit?js,output - Mohamed Sameer
3个回答

3

You can use Array.map() and use an array of properties, iterate over the array of properties and check for each object if that property is present in the object or not, if it is not present than simply add the property and assign it value as 0.

let arr = [ { name: 'test1', state: 'OK', status: true, pending: 33, approved: 0, active: 0, inactive: 33 }, { name: 'test3', state: 'OK', status: true, pending: 33, approved: 0, active: 0, inactive: 33 }, { name: 'test4', state: 'OK', status: true } ];
let props = ['active','inactive', 'approved', 'pending'];
let result = arr.map(a =>{
  props.forEach(prop=>  a[prop] = a[prop] || 0);
  return a;
});
console.log(result);


2
你可以使用.forEach将你的条件应用到每个对象。

arr = [
  {
    name: 'test1',
    state: 'OK',
    status: true,
    pending: 33,
    approved: 0,
    active: 0,
    inactive: 33
  },
  {
    name: 'test3',
    state: 'OK',
    status: true,
    pending: 33,
    approved: 0,
    active: 0,
    inactive: 33
  },
  {
    name: 'test4',
    state: 'OK',
    status: true
  }
]

arr.forEach(obj => {for (let p of ['pending', 'approved', 'active', 'inactive']){
                        if (!obj.hasOwnProperty(p)){
                            obj[p] = 0;
                        }
                   }});

console.log(arr);


1
  • 创建一个具有默认值属性的对象。
  • 使用 .map() 方法通过传递回调来迭代给定数组的对象。
  • 使用 Object.assign() 方法创建当前对象的副本,方法是通过传递空对象、默认对象和当前对象作为参数。首先将默认值复制到空对象中,然后 Object.assign() 将从当前对象复制每个属性到克隆对象中,有效地覆盖默认值。

下面是演示:

let data = [
  {name: 'test1',state:'OK',status:true,pending: 33,approved: 0,active: 0,inactive: 33},
  {name: 'test3',state:'OK',status:true,pending: 33,approved: 0,active: 0,inactive: 33},
  {name: 'test4',state:'OK',status:true}
];

let defaults = {
  pending: 0,
  approved: 0,
  inactive: 0,
  active: 0
};

let result = data.map(o => Object.assign({}, defaults, o));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

资源:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接