根据条件javascript

时间:2018-09-01 07:10:43

标签: javascript arrays json object

我的数组:

[
  {
    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
  }
]

该怎么做?

我尝试过地图,但是我不知道如何设置条件。

我想将值设置为零。

3 个答案:

答案 0 :(得分:3)

您可以使用Array.map()并使用属性数组,遍历属性数组并检查每个对象是否存在该对象,如果不存在,则只需添加该属性即可并将其值分配为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);

答案 1 :(得分: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);

答案 2 :(得分: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; }

资源: