4

I am a novice of 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.

I am using 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.

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.

2
  • Its a bit confusing. Can you please show us the expected output that you need? 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. Commented Apr 21, 2017 at 21:43

2 Answers 2

11

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.

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 comments:

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Since OP says he/she is a novice to ES6, I'd recommend that OP learn to use arrow functions for this (see below).
2

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;
});

3 Comments

You still need to return el, otherwise it's an array of undefined, no?
Actually index starts from 0 so we need to use ìndex+1 and this will always push indefined in the result array.
Yes, you need to return el. Edited. Index does start at 0. I'm assuming 0 is a valid Key for rc-table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.