1

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.

0

5 Answers 5

3

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

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

Comments

0

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

Comments

0

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

Comments

0

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]});
}, []);

Comments

0

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

Comments

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.