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
4 Answers
Reset to default 3Just 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
版权声明:本文标题:javascript - Rename nested key in array of objects JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745016643a2637882.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论