0

I have an object in Javascript. I want to add key-value pair in it.

var data = {
  Country1: '20',
  country2: '30',
  country3: '40',
  country4: '45'
};

It should look like,

var data = {
  {name: 'country1', values: '20'},
  {name: 'country2', values: '30'},
  {name: 'country3', values: '40'},
  {name: 'country4', values: '45'},
};

I am looking for a solution where from a given object, country names will automatically fall into name and values into values

2
  • 1
    use Array.map() function. Such questions were asked many times on SO Commented Dec 23, 2017 at 13:43
  • how do you grant the order of the keys? Commented Dec 23, 2017 at 14:35

3 Answers 3

6

Iterate the Object#keys of the object with Array#map, and return an object in the format that you want.

Note: to ensure the order of the objects, you can sort the keys using String#localeCompare with the numeric: true option.

var data = {
    'Country1' : '20',
    'country2': '30',
    'country3': '40',
    'country4' : '45'
};

var result = Object.keys(data)
  .sort(function(a, b) { // if you need to ensure the order of the keys
    return a.localeCompare(b, undefined, { numeric: true})
  })
  .map(function(key) {
    return {
      name: key,
      value: data[key]
    };
  });

console.log(result);

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

Comments

0

Use Objecy.Keys and forEach to loop through the Objects,

var data = {
    'Country1' : '20',
    'country2': '30',
    'country3': '40',
    'country4' : '45'
};
var result = [];
Object.keys(data).forEach(key => {
    result.push({'name':key,'value':data[key]});
    
});
console.log(result);

1 Comment

There's Array.prototype.map() for this exact case.
0

or use Object.entries :

 data = Object.entries(data).map(([name, values]) => ({name, values}));

2 Comments

Could you update your answer and explain what you are doing. Many thanks in advance
@mzaragoza i just convert the returned 2darray into an array of objects using array destructuring and ES2015 object literals.

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.