I am a novice of ES6 JavaScript. I am looking for a scenario where i can update an object array that is ing from a web service and pass the data format to a table.
I am using ReactJS 'rc-table'.
To display our data in the rc-table format , We need to have an attribute key:"somevalue" in our data that is ing from the backend.
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.
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. Any help would be appreciated.
I am a novice of ES6 JavaScript. I am looking for a scenario where i can update an object array that is ing from a web service and pass the data format to a table.
I am using ReactJS 'rc-table'.
https://www.npmjs./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 ing from the backend.
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.
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. Any help would be appreciated.
Share Improve this question edited Apr 21, 2017 at 21:43 mohan babu asked Apr 21, 2017 at 21:38 mohan babumohan babu 1,4482 gold badges19 silver badges36 bronze badges 2- Its a bit confusing. Can you please show us the expected output that you need? – Akshay Khandelwal Commented Apr 21, 2017 at 21:39
- There is nothing in ES6 that would make this easier. You can use any solution you used before in ES5. – Felix Kling Commented Apr 21, 2017 at 21:43
2 Answers
Reset to default 11Well 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.
This is how you should write your code:
var data = arr.map(function(item, index) {
item.key = index + 1;
return item;
});
ES6 Solution:
Using ES6 arrow functions as suggested by Chester Millisock in ments:
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;
});