Mike Will
Mike Will

Reputation: 309

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
}))

Upvotes: 3

Views: 2940

Answers (4)

trincot
trincot

Reputation: 350272

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.

Upvotes: 3

ZER0
ZER0

Reputation: 25322

If it's indeed a JSON (as your tag seems to indicate), e.g. you get it as string from a server, you can use a reviver function, such as:

var prod = JSON.parse(prodJSON, function (k, v) {
 if (k === "canBook") {
   this["quantity"] = v
 } else {
   return v
 }
});

(Of course you could always stringify in case you start from a JS Object and not from a JSON string, but in that case it would be an overkill)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386578

You could take a recursiv approach with an object for the renamed properties and build new object or arrays.

function rename(value) {
    if (!value || typeof value !== 'object') return value;
    if (Array.isArray(value)) return value.map(rename);
    return Object.fromEntries(Object
        .entries(value)
        .map(([k, v]) => [keys[k] || k, rename(v)])
    );
}

var keys = { canBook: 'quantity', variationsEN: 'variations', valueEN: 'value' },
    prod = [{ price: 10, canBook: 1 }, { price: 11, canBook: 2, variationsEN: [{ valueEN: 1 }, { valueEN: 2 }] }],
    result = rename(prod);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Peter
Peter

Reputation: 68

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

Upvotes: 0

Related Questions