mahipal singh
mahipal singh

Reputation: 364

convert javascript Associative Array to multi object array

here is my input:

where input may receive more data like 'e:5'

  var input = {a:2,b:3,c:2,d:1};

I want to convert this input into below output:

var output = [{name="a",id="2"},
              {name="b",id="3"},
              {name="c",id="2"},
              {name="d",id="1"}];

thanks in advance.

Upvotes: 1

Views: 625

Answers (5)

Lewis
Lewis

Reputation: 14866

Javascript object properties are unordered. Because of that, the order of keys returned from Object.keys is undetermined. In order to maintain the alphabetical order like your example, you need to previously sort the keys , then use map to create a new array with the expected value.

I don't like ES5. So here is my ES6 answer.

Object.keys(input).sort((a, b) => a.localeCompare(b)).map(name => ({name, id: input[name]}));

Upvotes: 0

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

You can also try below approach :

var input = {a:2,b:3,c:2,d:1};

var output = Object.keys(input).reduce(function(p, c){
     return p.concat({name:c, id:input[c]});
}, []);

Upvotes: 0

Redu
Redu

Reputation: 26161

Just for some fun and for training purposes we may come up with this. Remember that while it's possible to add later, you can always embed a Symbol.iterator method by the constructor function at the time of instantiation and your objects become iterable by default.

var input = {a:2,b:3,c:2,d:1},
   output = [];
input[Symbol.iterator] = function*(){
                           var ok = Object.keys(this),
                                i = 0;
                           while (i < ok.length) yield {[ok[i]]: this[ok[i++]]};
                         };
for (var keyValuePair of input) output.push(keyValuePair);
console.log(output);

// or you can even do like
output.length = 0;
output = [...input]; // cool
console.log(output);

Upvotes: 0

Rayon
Rayon

Reputation: 36609

Use Array#map over Object.keys

The Object.keys() method returns an array of a given object's own enumerable properties.


The map() method creates a new array with the results of calling a provided function on every element in this array.


var input = {
  a: 2,
  b: 3,
  c: 2,
  d: 1
};

var mapped = Object.keys(input).map(function(key) {
  return {
    name: key,
    id: input[key]
  };
});
console.log(mapped);

Upvotes: 3

Vladu Ionut
Vladu Ionut

Reputation: 8183

Use can Array#forEach over Object.keys

var input = {a:2,b:3,c:2,d:1};
var output = [];
Object.keys(input).forEach(function(key){
  output.push({name:key,id:input[key]});
  })
console.log(output);

Upvotes: 0

Related Questions