I am working on project where I need to maintain an array from json data returned from API, json can have tree, I have following code which is working fine but I wan to remove if conditions before assigning values to array elements
// data contains json
let newArray = []
for(let d in data){
for(let x in data[d]){
if(typeof(newArray[d]) === 'undefined'){
newArray[d] = []
}
if(typeof(newArray[d][data[d][x]['id']]) === 'undefined'){
newArray[d][data[d][x]['id']] = []
}
newArray[d][data[d][x]['id']]['price'] = data[d][x]['price']
newArray[d][data[d][x]['id']]['discount'] = data[d][x]['discount']
}
}
In above code I have to check the array first and declare it as array if its not otherwise it returns undefined error, is there any way to get rid of there conditions and extend array as per requirement ?
newArray[d]
looks suspicious. I hopenewArray
will not become a sparse array? (if so, use an object instead) You can make the code more DRY by storing the repetitive expressions in variablesdata[d][x]['id']
? Is it a string or is it a number ?let newArray = {}
but it has same issuelet arr = []; arr['prop1'] = 'val1';
without complaining. But the problem is with serialization. If you try toJSON.stringify()
such a thing, only number-like indexes will be kept in the result. For storing key-value pairs there are object literals ({ key1: 'value1' }
) and this is what you should use here. Regarding your case, if you expect thatlet o = {}; o.prop1.prop2 = 'val1'
will create{ prop1: { prop2: 'val1' } }
then the answer is no, you can't do that without additional effort.