I'm trying to create an object with multiple key-pair values inside.
The values I'm using will be be ing 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: {
.....
}
}]
I'm trying to create an object with multiple key-pair values inside.
The values I'm using will be be ing 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: {
.....
}
}]
Share
Improve this question
edited Jan 6, 2019 at 2:10
Jack Bashford
44.2k11 gold badges55 silver badges82 bronze badges
asked Jan 6, 2019 at 1:58
RickRick
2,2814 gold badges20 silver badges33 bronze badges
4
-
2
It's not clear what you are starting with. Keys in Objects are unique, so looping over an array and setting
user_name
on the same object will only set oneuser_name
. It might help if you can give an example of thejson_users
. If you are trying to useuser_name
as the key, put it in brackets{[user_name]: values}
– Mark Commented Jan 6, 2019 at 2:04 - Could you please add an example of this code you’re looping through, as we don’t know what you started with. – Jack Bashford Commented Jan 6, 2019 at 2:07
- I simply want to be able to create an object that will contain values without an index when pushing to it. Like `{"k1":v1, "k2":v2} instead if {[ [0] {"k1":v1} [1] {"k2":v2} ]} – Rick Commented Jan 6, 2019 at 2:08
- 1 @M. Duisenbayev has already answered my question – Rick Commented Jan 6, 2019 at 2:17
2 Answers
Reset to default 5var 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
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;
})