3

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
}))
1
  • You cannot "rename" the property of an object. You can only add a new and delete the old one. Commented Mar 21, 2020 at 15:07

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sounds good, but I got TypeError: p.variationsEN is undefined
Then the data is not as you depicted in your question. In that case you need to first test for the property's existence. See update.
2

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

Comments

1

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)

Comments

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

2 Comments

Sounds good, but I got TypeError: p.variationsEN is undefined
It can happen if you don't pass the second argument or the second argument is undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.