[英]How to check if objects in an array of objects all have specific structure and are not a null?
I receive an array of objects from the server. 我从服务器接收到一系列对象。 But my app breaks because some objects do not have a structure just a null value and my logic depends on checking against certain object keys to do one thing or another.
但是我的应用程序中断了,因为某些对象没有仅具有null值的结构,并且我的逻辑依赖于检查某些对象键来做一件事或另一件事。 Here is an example of an array that i receive:
这是我收到的数组的示例:
[{
clienTnames: {
firstName: 'Jack',
lastName: 'Jackson'
}
}, {
clienTnames: {
firstName: 'John',
lastName: 'Johnson'
}
}, {
clienTnames: null
}]
I would like to check if any objects arrive as null and if they do switch them to empty object with all the proper keys just with no value. 我想检查是否有任何对象作为null到达,以及是否确实使用所有正确的键将它们切换为空对象而没有任何值。 So if I receive clienTnames: null;
因此,如果我收到clienTnames:null; I would like to automatically change it to clienTnames : {firstName: ' ', lastName: ' '}
我想将其自动更改为clienTnames:{firstName:'',lastName:''}
Just use a map function: 只需使用一个地图功能:
names = names.map(name => {
return name.clienTnames
? name.clienTnames
: { clienTnames: { firstName: '', lastName: '' } }
});
You can create a defaultObj
with all the default properties. 您可以使用所有默认属性创建一个
defaultObj
。 Then loop through the array and update items which have clienTnames
property set to null 然后遍历数组并更新将
clienTnames
属性设置为null的项目
let array = [{clienTnames:{firstName:'Jack',lastName:'Jackson'}},{clienTnames:{firstName:'John',lastName:'Johnson'}},{clienTnames:null}] const defaultObj = { firstName: '', lastName: '' } array.forEach(a => { if(!a.clienTnames) a.clienTnames = { ...defaultObj } }) console.log(array)
You can do something like this: 您可以执行以下操作:
const data = [{ clienTnames: { firstName: 'Jack', lastName: 'Jackson' } }, { clienTnames: { firstName: 'John', lastName: 'Johnson' } }, { clienTnames: null }]; let output = []; output = data.map(element => { if (element.clienTnames) { return element; } else { return { clienTnames: { firstName: '', lastName: '' } }; } }); console.log(output);
let array = [{
clienTnames: {
firstName: 'Jack',
lastName: 'Jackson'
}
}, {
clienTnames: {
firstName: 'John',
lastName: 'Johnson'
}
}, {
clienTnames: null
}];
let targetArray;
targetArray = array.map((item) => {
if(!item.clienTnames) {
return { clienTnames: { firstName: '', lastName: '' } }
}
return item;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.