我有以下对象数组。我想将关键“文本”更改为名称标签
[
{id: 0, text: "blue"},
{id: 1, text: "green"},
{id: 2, text: "orange"},
{id: 3, text: "yellow"}
]
“id”必须保持原样。
我可以使用lodash或javascript。
答案 0 :(得分:3)
您可以使用.map()
方法重命名对象数组中的键。
var data = [
{id: 0, text: "blue"},
{id: 1, text: "green"},
{id: 2, text: "orange"},
{id: 3, text: "yellow"}
]
data = data.map(el => {
return {
id: el.id,
label: el.text
}
})
console.log(data);
答案 1 :(得分:2)
你可以使用.map
let arr=[
{id: 0, text: "blue"},
{id: 1, text: "green"},
{id: 2, text: "orange"},
{id: 3, text: "yellow"}
];
let arr1=[];
arr1=arr.map(a=>({id:a.id,label:a.text}));
console.log(arr1);
答案 2 :(得分:1)
您可以使用函数forEach
和带有目标的数组
此替代方案将改变原始数组。
let array = [{id: 0, text: "blue"},{id: 1, text: "green"}, {id: 2, text: "orange"}, {id: 3, text: "yellow"}],
target = [['text', 'label'], ['ele', 'stack']];
array.forEach(o => {
target.forEach(([src, dest]) => {
if (o[src]) {
Object.assign(o, {[dest]: o[src]});
delete o[src];
}
});
});
console.log(array);

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