Asked  7 Months ago    Answers:  5   Viewed   37 times

I want to convert an object like this:

{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}

into an array of key-value pairs like this:

[[1,5],[2,7],[3,0],[4,0]...].

How can I convert an Object to an Array of key-value pairs in JavaScript?

 Answers

99

You can use Object.keys() and map() to do this

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key), obj[key]]);

console.log(result);
Tuesday, June 1, 2021
 
rlanvin
answered 7 Months ago
52

At the time of writing (2013) JavaScript objects / dictionaries / associative arrays don't have such a constructor natively.

As you said yourself, you can of course build your own function using for instance a functional approach using the reduce function as explained in one of the other answers. A classic for or newer forEach loop would also work, of course. But there isn't anything built-in.


Edit: It's 2019 and now we have Object.fromEntries, which will give you what you need.

Monday, June 7, 2021
 
BradM
answered 6 Months ago
50

Try the following

var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];

var myTotal = 0;  // Variable to hold your total

for(var i = 0, len = myData.length; i < len; i++) {
    myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up
}

document.write(myTotal); // 22 in this instance
Tuesday, June 29, 2021
 
Fernando
answered 6 Months ago
82

You can use Object.keys(obj) to get named indexes. This will return an array structure which you can use/customize further. A sample use to iterate over object values may look like this

var persons = { 
    john: { age: 23, year:2010},
    jack: { age: 22, year:2011},
    jenny: { age: 21, year:2012}
}

Getting an iterator

var resultArray = Object.keys(persons).map(function(personNamedIndex){
    let person = persons[personNamedIndex];
    // do something with person
    return person;
});

// you have resultArray having iterated objects 
Thursday, July 29, 2021
 
erotsppa
answered 5 Months ago
44

I was able to reproduce the client.page.signinPage is not a function error. When I change the page_objects_path from pages to built/pages (because I presume Nightwatch is looking for JavaScript files and not TypeScript files), that error goes away and I get a different error, which I believe is because I don't have the browser driver installed correctly. Try changing the page_objects_path and hopefully your tests will work.

Friday, September 3, 2021
 
user2923558
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share