[英]How would I use _.mapKey over this array of objects
我有以下对象数组。 我想将键“文本”更改为标签
[
{id: 0, text: "blue"},
{id: 1, text: "green"},
{id: 2, text: "orange"},
{id: 3, text: "yellow"}
]
“ id”必须保持原样。
我可以使用lodash或javascript。
您可以使用.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);
您可以使用.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);
您可以将函数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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.