Codeleys
Codeleys

Reputation: 45

Add key-value pair in Javascript object

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

Upvotes: 0

Views: 5023

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

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

Upvotes: 6

Jonas Wilms
Jonas Wilms

Reputation: 138257

or use Object.entries :

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

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222572

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

Upvotes: 0

Related Questions