I have an api that returns a nested object of this form:
obj: {
nestedobj1: {
name: 'a',
prop2: 'b',
prop3: 'c',
prop4: 'd'
},
nestedobj2: {
name: 'a',
prop2: 'b',
prop3: 'c',
prop4: 'd'
},
nestedobj3: {
name: null,
prop2: null,
prop3: null,
prop4: null
},
nestedobj4: {
name: null,
prop2: null,
prop3: null,
prop4: null
},
// and so on up to 15 nested objects whose internal properties are null
}
These nested objects are supposed to hold a row of table data. When the user enters the details for the fields, the inputs need to be saved in one of the nested object for which the name value is null. How do I achieve this in javascript?
If I understand correctly, you want to extract the first a key/value entry from obj
where the value object itself contains any null
values.
One way to achieve that would be to:
obj
via Object.entries()
and then,null
values (this can be done using Object.values()
and .some()
- see snippet below),This could be expressed in code as:
const obj={nestedobj1:{name:'a',prop2:'b',prop3:'c',prop4:'d'},nestedobj2:{name:'a',prop2:'b',prop3:'c',prop4:'d'},nestedobj3:{name:null,prop2:null,prop3:null,prop4:null},nestedobj4:{name:null,prop2:null,prop3:null,prop4:null}}; /* Pluck first value from result array, if any */ const [ firstObjectWithNull ] = Object.entries(obj) /* Filter/find any key/value entries from state object where object values have any nulls */ .filter(entry => { const [key, object] = entry; const objectValues = Object.values(object); /* With "some()", find the first entry where the values of the object have a null */ return objectValues.some(value => value === null); }) .map(entry => { /* Reconstuct any fiiltered entries to key/value objects */ const [key, object] = entry; return { [key] : object }; }); console.log(firstObjectWithNull);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.