admin管理员组

文章数量:1410717

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

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
}))
Share asked Mar 21, 2020 at 15:05 Mike WillMike Will 3092 silver badges15 bronze badges 1
  • You cannot "rename" the property of an object. You can only add a new and delete the old one. – Andreas Commented Mar 21, 2020 at 15:07
Add a ment  | 

4 Answers 4

Reset to default 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.

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

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)

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

本文标签: javascriptRename nested key in array of objects JSStack Overflow