2

I'm trying to convert object

var data = {"USD": 12323,"CAD":32123}

to become

[{"id":"USD","value":12323},{"id":"CAD","value":32123}]

This is what i tried so far

var res = Object.keys(data).map(function(k) { 
    return [k, result[k]];
});

and get the result

[["USD", 12323],["CAD", 32123]]

Any help is very appreciated.

Thanks,

3
  • 1
    Instead of this: return [k, result[k]] do return { id: k, value: result[k] } Commented Dec 28, 2017 at 10:14
  • 1
    @gurvinder372 I dont think so. I haven't looked for it actually. Just that I like to make answers a bit descriptive. So for such cases, I prefer comments. Will try to answer instead from next time. Thanks for asking. :-) Commented Dec 28, 2017 at 10:18
  • stackoverflow.com/questions/47952992/… Commented Dec 28, 2017 at 10:44

5 Answers 5

2

Just change your return statement to

return {id: k, value:result[k]}; //observe that an object is returned instead of an array

Demo

var data = {"USD": 12323,"CAD":32123};
var res = Object.keys(data).map(function(k) { 
   return {id: k, value:data[k]};
});
console.log( res );

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

Comments

1

You're creating one array, not an object. Change [] to {}:

var res = {"USD": 12323,"CAD":32123};

res = Object.keys(res).map(function(k) { 
    return {id: k, value:res[k]};
});

console.log(res);

as an alternative, you can use arrow function:

var res = {"USD": 12323,"CAD":32123};

res = Object.keys(res).map(x => x = { id: x, value: res[x]});

console.log(res);

or .every():

var res = {"USD": 12323,"CAD":32123};

var resWArrow = Object.entries(res).map(function(k) { 
    return {id: k[0], value: k[1]};
});

console.log('Without arrow: ' + JSON.stringify(resWArrow));

var resArrow = Object.entries(res).map(x => x = { id: x[0], value: x[1] });

console.log('With arrow: ' + JSON.stringify(resArrow));

Comments

1

With ES6, you could take Object.entries with Array#map and a destructuring assignment for the elements and short hand properties for the result.

var data = { "USD": 12323, "CAD": 32123 },
    result = Object.entries(data).map(([id, value]) => ({ id, value }));
    
console.log(result);

Comments

0

You can iterate over the keys of the object and map them like follows:

Object.keys(res).map(function(key) { 
    return {id: key, value: data[key]};
}

Comments

0

Change the return statement and return an object

var res = {
  "USD": 12323,
  "CAD": 32123
}
var m = Object.keys(res).map(function(item) {
  return {
    id: item,
    value: res[item]
  }

})
console.log(m)

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.