Search code examples
javascriptarraysjsonjavascript-objects

Rename nested key in array of objects JS


Using JS i am trying to rename canBook -> quantity, variationsEN -> variations and nested keys valueEN -> value

var prod = [{
    price: 10,
    canBook: 1
}, {
    price: 11,
    canBook: 2,
    variationsEN: [{
        valueEN: 1
    }, {
        valueEN: 2
    }]
}]

I was able to rename keys, but i dont have a clue how to rename the nested ones: valueEN

prod.map(p => ({
    quantity: p.canBook, variations:p.variationsEN
}))

Solution

  • Just apply the same trick again. Replace:

    variations:p.variationsEN
    

    with:

    variations:(p.variationsEN || []).map(q => ({ value: q.valueEN }))
    

    The additional || [] is to deal with cases where the property does not exist in your source object. In that case an empty array is produced for it.