Vikram
Vikram

Reputation: 3351

How to extend an array with new array without declaration

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 ?

Upvotes: 2

Views: 118

Answers (2)

Aviso
Aviso

Reputation: 695

You can you new ES6 spread operator like this

newAraay[d] = [...newArray,...Array(data[d][x]['id']),[...Array('price',data[d][x]['price'])]]

Like here in this snippet I am directly doing abc[1][3][4] = "new value" without explicitly initialising them

let abc = [];
abc[1]=  [...abc,...Array(3),[...Array(4),'new inserted value']]
console.log(abc);

Upvotes: 2

CodeBanBan
CodeBanBan

Reputation: 48

newArray[d] = newArray[d] || []

You can understand this operation in this post

Or use Lodash Library

https://lodash.com/docs/4.17.11#set

Upvotes: 1

Related Questions