[英]Updating an existing object Array in ES6 javascript
I am a novice of ES6 JavaScript.我是 ES6 JavaScript 的新手。 I am looking for a scenario where i can update an object array that is coming from a web service and pass the data format to a table.
我正在寻找一种方案,我可以在其中更新来自 Web 服务的对象数组并将数据格式传递给表。
I am using ReactJS 'rc-table'.我正在使用 ReactJS 'rc-table'。
https://www.npmjs.com/package/rc-table
To display our data in the rc-table format , We need to have an attribute key:"somevalue" in our data that is coming from the backend.要以 rc-table 格式显示我们的数据,我们需要在来自后端的数据中有一个属性 key:"somevalue"。
My data is in the following format:我的数据格式如下:
{
{
Name:'Robert',
City: 'Barcelona'
},
{
Name: 'Marguaritte',
City: 'Baltimore'
}
}
Now it will display in rc-table format , only if the object has a unique key attribute.现在它将以 rc-table 格式显示,仅当对象具有唯一键属性时。
For Example:例如:
{
{
Name:'Robert',
City: 'Barcelona',
Key:1
},
{
Name: 'Marguaritte',
City: 'Baltimore',
Key:2
}
}
I am looking for updating my object with 'key:1' and 'key:2' Attached is my code.我正在寻找用“key:1”和“key:2”更新我的对象附加的是我的代码。 Any help would be appreciated.
任何帮助,将不胜感激。
Well your actual array format is incorrect, you should replace wrapping {}
with []
so it's a valid array.好吧,您的实际数组格式不正确,您应该将
{}
替换为[]
这样它就是一个有效的数组。
Anyway you should use Array.prototype.map() , it will return a customised array using a callback function that will add the key
property to each iterated item.无论如何,您应该使用Array.prototype.map() ,它将使用回调函数返回一个自定义数组,该回调函数会将
key
属性添加到每个迭代项。
This is how you should write your code:这是您应该如何编写代码:
var data = arr.map(function(item, index) {
item.key = index + 1;
return item;
});
ES6 Solution: ES6 解决方案:
Using ES6 arrow functions as suggested by Chester Millisock in comments:使用Chester Millisock在评论中建议的ES6 箭头函数:
var data = arr.map((item, index) => {
item.key = index + 1;
return item;
});
Demo:演示:
var arr = [{ Name: 'Robert', City: 'Barcelona' }, { Name: 'Marguaritte', City: 'Baltimore' } ]; var data = arr.map((item, index) => { item.key = index + 1; return item; }); console.log(data);
I think you want to do something like this.我想你想做这样的事情。 I'm assuming your data is an array of objects and not an object without keys, as you suggested.
我假设您的数据是一个对象数组,而不是您建议的没有键的对象。
const data = data.map((el, index) => {
el.Key = index;
return el;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.