[英]delete previous object fields and make new fields in array of objects in javascript
I have a list of objects in javascript where I have a list with 1 field which is org_name like this:我在 javascript 中有一个对象列表,其中有一个包含 1 个字段的列表,它是 org_name,如下所示:
const list=[
{ org_name:"Test1"},
{ org_name:"Test2"}
]
Now I want to change this list to:现在我想将此列表更改为:
const list=[
{ text:"Test1",value:"Test1"},
{ text:"Test2",value:"Test2"}
]
What I am doing is:我正在做的是:
list.map(el => ({ ...el, text: el.org_name, value: el.org_name }));
Its not working,Any leads will be appreciated.它不起作用,任何线索将不胜感激。
Just drop the ...el
part since you don't need it.只需删除
...el
部分,因为您不需要它。
const list=[ { org_name:"Test1"}, { org_name:"Test2"} ]; const out = list.map(el => { return { text: el.org_name, value: el.org_name }; }); console.log(out);
Array.map
creates new array. Array.map
创建新数组。 You want to update existing array, so loop through the array and update the object keys.您想要更新现有数组,因此遍历数组并更新 object 键。
const list = [ { org_name: "Test1" }, { org_name: "Test2" } ]; list.forEach(el => { el.text = el.org_name; el.value = el.org_name; delete el.org_name; }); console.log(list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.