0

How covert or add each key and value into separate array.

Now

var arr = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
}

Result should be

var arr = [
  ["3/10/2017", 52],
  ["3/11/2017", 58],
  ["3/12/2017", 70],
  ["3/13/2017", 76]
]

Thank you

4
  • array not with keys and values .its only have a arguments Commented Apr 10, 2017 at 9:32
  • 3
    ["3/10/2017": 52] isn't valid JavaScript. Did you mean {"3/10/2017": 52} instead? Commented Apr 10, 2017 at 9:32
  • If you wanted [["3/10/2017", 52],... - then it's as easy as Object.entries(arr) - however, what you want is invalid Commented Apr 10, 2017 at 9:34
  • Please respecify what you want exactly Commented Apr 10, 2017 at 9:36

3 Answers 3

4

["3/13/2017": 76] is actually invalid array, but you could replace : with e.g. comma , or just push it to every array as an object.

var arr = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
},
res = Object.keys(arr).map(v => new Array(v, arr[v])),
res2 = Object.keys(arr).map(v => new Array({[v]: arr[v]}));

console.log(JSON.stringify(res, 2, null));
console.log(JSON.stringify(res2, 2, null));

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

2 Comments

This is because IE does not support arrow functions.
@ArunKumarM And that was the reason to unaccept my answer? Note that you didn't mention anything about compatibility with IE. You could just tell me it instead of unaccepting my answer. This is just wrong and you have disappointed me.
3

using Object.entries

var arr = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
};

arr = Object.entries(arr);
console.log(JSON.stringify(arr));

2 Comments

Object.entries method is unfortunately not supported by IE or Opera. At all.
Polyfills change that sad state of affairs
2

You should use map method in combination with Object.keys().map method accepts a callback function which is applied to every item in the array.

var arr = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
};
console.log(Object.keys(arr).map(function(item){
    return [item,arr[item]];
}));

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.