数组包含存储在空值的其他一些部分中的空值


var dataList = [ 
{ date: '2019-08-08', class: null, users: 21 },
{ date: '2019-08-08', class: 'lower', users: 21 },  
{ date: '2019-08-08', class: 'upper', users: 3}
{ date: '2019-08-08', class: 'middle', users: 5}
];

如果数组键包含我想像这样存储null我想要这个 我在数组中有多个日期,每个数组包含一个空值

store null into "Others" key 
var dataList = [ 
{ date: '2019-08-08', class: 'Others', users: 21 },
{ date: '2019-08-08', class: 'lower', users: 21 },  
{ date: '2019-08-08', class: 'upper', users: 3}
{ date: '2019-08-08', class: 'middle', users: 5}
];

使用forEach循环

var dataList = [ 
{ date: '2019-08-08', class: null, users: 21 },
{ date: '2019-08-08', class: 'lower', users: 21 },  
{ date: '2019-08-08', class: 'upper', users: 3},
{ date: '2019-08-08', class: 'middle', users: 5}
];
dataList.forEach(function(e){
if(e.date==null)
e.date='Others'
if(e.class==null)
e.class='Others'
if(e.users==null)
e.users='Others'
})
console.log(dataList)

像这样使用map


var dataList = [ 
{ date: '2019-08-08', class: null, users: 21 },
{ date: '2019-08-08', class: 'lower', users: 21 },  
{ date: '2019-08-08', class: 'upper', users: 3},
{ date: '2019-08-08', class: 'middle', users: 5}
];
const res = dataList.map(({ class: c, ...r }) => ({ class: c == null ? "Other" : c, ...r }));
console.log(res);

使用array.map()

map(( 方法创建一个新数组,其中包含对调用数组中的每个元素调用提供的函数的结果。

var dataList = [ 
{ date: '2019-08-08', class: null, users: 21 },
{ date: '2019-08-08', class: 'lower', users: 21 },  
{ date: '2019-08-08', class: 'upper', users: 3},
{ date: '2019-08-08', class: 'middle', users: 5}
];

let newList = dataList.map( (obj) => obj.class == null? { ...obj, class: "Other" } : obj );

如果您需要检查 obj 中的任何键,而不仅仅是class键 - 在此处评论,我将编辑我的答案。

这是非常简单的代码如下

dataList=dataList.map(x=>{x.class=x.class||"Others";return x})

var dataList = [ 
{ date: '2019-08-08', class: null, users: 21 },
{ date: '2019-08-08', class: 'lower', users: 21 },  
{ date: '2019-08-08', class: 'upper', users: 3},
{ date: '2019-08-08', class: 'middle', users: 5}
];

dataList=dataList.map(x=>{x.class=x.class||"Others";return x})
console.log(dataList)

相关内容

  • 没有找到相关文章