根据条件javascript将其他对象键添加到数组中

问题描述 投票:4回答:3

我的阵列:

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

这该怎么做?

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

我想将值设置为零。

javascript arrays json object
3个回答
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);

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; }

资源:

© www.soinside.com 2019 - 2024. All rights reserved.