5

Given the following arrays:

var ids = [1,2,3]; //Hundreds of elements here
var names = ["john","doe","foo"]; //Hundreds of elements here
var countries = ["AU","USA,"USA"]; //Hundreds of elements here

What's the best way performance-wise to generate an array of objects with a similar structure to this:

var items = [
    {id:1,name:"john",country:"AU"},
    {id:2,name:"doe",country:"USA"},
    ...
];
3
  • 1
    If there's one thing I can't say enough on SO, it's this: make it work first, then worry about performance if and only if performance becomes an issue. How would you solve this if you weren't concerned about performance? Commented Nov 11, 2016 at 0:57
  • What kind of performance? Run-time? Memory? Lines of code? Writability/maintainability? Commented Nov 11, 2016 at 3:53
  • I am wondering where you were getting stuck, since a simple solution is to loop from 0 to 2, then each time through the loop push an object containing the relevant values onto a results array. Once you've figured that out, you can move on to using map etc. Commented Nov 11, 2016 at 3:56

2 Answers 2

20

You should be able to simply map through all ids, keeping a reference to your index, and build your object based on that index.

var items = ids.map((id, index) => {
  return {
    id: id,
    name: names[index],
    country: countries[index]
  }
});
Sign up to request clarification or add additional context in comments.

Comments

-1

This is what I get when run the code:

[
    { country=AU, name=john, id=1.0 }, 
    { name=doe, country=USA, id=2.0 }, 
    { id=3.0, country=USA, name=foo }
]

Following is the code, same as @Zack Tanner

function arrs2Obj() {
    var ids = [1, 2, 3]; //Hundreds of elements here
    var names = ["john", "doe", "foo"]; //Hundreds of elements here
    var countries = ["AU", "USA", "USA"]; //Hundreds of elements here

    var items = ids.map((id, index) => {
        return {
            id: id,
            name: names[index],
            country: countries[index]
        }
    });
    Logger.log(items)
}

The problem is, this result is not sorted as the questioner asked. I mean it's not consistent - ids to be the first item, name second, country 3rd; this way it is more presentable.

1 Comment

Just want to add that the ordering of fields in an object is not guaranteed. As per the JSON standard, "An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array." - rfc-editor.org/rfc/rfc8259.html#section-1

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.