Rick
Rick

Reputation: 2271

How do I create a single object and push multiple key-pair values inside?

I'm trying to create an object with multiple key-pair values inside.

The values I'm using will be be coming from an API and I'm trying to convert the response into a single object.

My code:

json_users.forEach(function (user){
    var user_name = user.name;
    var object_user = {user_name: null};

    temp_collection.push(object_user);
})

The kind of result I want

{"key_1":val_1, "key_2", val_2}

The result I get

[{
    0: {
        .....
    }, 
    1: {
        .....
    }
}]

Upvotes: 1

Views: 3598

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44107

You shouldn’t use .push() - this is creating the array. Try this instead:

var temp_collection = {};
json_users.forEach((user, index) => temp_collection[`key_${index}`] = user.name);

This iterates through the array json_user and adds a new property to the temp_collection object with the name property of each object in the array.

The above does use ES6 arrows and template literals though, so here’s a more widely accepted version:

json_users.forEach(function(user, index) {
    temp_collection["key_" + index] = user.name;
})

Upvotes: 3

M. Duisenbayev
M. Duisenbayev

Reputation: 319

var resultObject = {};
json_users.forEach(function (user, index){
    var user_name = user.name;
    var object_user = {user_name: null};

    resultObject["key" + (index + 1)] = object_user;
});

resultObject will be what you need. Instead of "key" + (index + 1) you can use user.id or something like that. This way you will have a dictionary of users, where keys will be IDs and values will be user objects

Upvotes: 5

Related Questions