Dreams
Dreams

Reputation: 8506

How to map a Array and create a Object from it?

Below is my code....

var temp = {};
[{group_id : "1111"}, {group_id: "2222"}].map(function(ele, index) {
    var group_id = ele.group_id;
    temp.group_id = {value: 0}
});

After run this code, the temp object is

 {group_id : {value : 0}

But what I want is

{ {"1111" : {value : 0}}, {"2222" : {value : 0}} }

How can I do that?

Upvotes: 0

Views: 57

Answers (5)

ajaykumar
ajaykumar

Reputation: 656

You can use the reduce Fn to reduce your array to object. As the expectation of your output is not a valid JSON, the result of a valid JSON structure that can be obtained is below. Pls modify your question for a valid result set if this is not the case.

var temp = [{group_id : "1111"}, {group_id: "2222"}].reduce(function(obj, key) {
	
     obj[key.group_id] = {value: 0};
     return obj;
    
} , {});
console.log(temp);

Upvotes: 0

Pankaj
Pankaj

Reputation: 966

Your map function is fine, though the structure of object that you wanna achieve is little bit wrong.

In a object, the values exist as key-value pair, so there has to be a key against the temp object. Or you can enclose everything as an array.

SO

var temp = {};
[{group_id : "1111"}, {group_id: "2222"}]
.map(function(ele) {
    var group_id = ele.group_id;
    temp[group_id] = {value: 0}
});
will give you temp as

{"1111":{value: 0}, "2222":{value: 0}}

And for array, your code can go like following:

var temp = [];
[{group_id : "1111"}, {group_id: "2222"}]
.map(function(ele) {
  var obj = {};
  obj[ele.group_id] = {value: 0}
  temp.push(obj)
});

This will give you temp as

[{"1111":{value: 0}}, {"2222": {value: 0}}]

You can use any one of them, both are good, though depends on how you wanna use temp later in you code.

Upvotes: 0

Samuel Toh
Samuel Toh

Reputation: 19328

As your current noted expected result is not a valid JSON structure.

Instead I am writing my solution based on the assumption that your expected result is:
{ "1111" : {value : 0}, "2222" : {value : 0} } and since the end result is an object, using map would not be appropriate as it returns an Array. So my solution is based on the reduce API.

function initObject(obj, currElement) {
  obj[currElement.group_id] = { value: 0 };
  return obj;
}

console.log([{group_id : "1111"}, {group_id: "2222"}].reduce(initObject, {}));

Upvotes: 0

guest271314
guest271314

Reputation: 1

But what I want is

{ {"1111" : {value : 0}}, {"2222" : {value : 0}} }

You can utilize an array to store objects where results would be

[
  {
    "1111": {
      "value": 0
    }
  },
  {
    "2222": {
      "value": 0
    }
  }
]

var obj = [{group_id : "1111"}, {group_id: "2222"}];
var res = obj.map(o => ({[o.group_id]:{value:0}}));

Upvotes: 0

Sudharsan Selvaraj
Sudharsan Selvaraj

Reputation: 4832

instead of using temp.group_id use temp[group_id].

Upvotes: 1

Related Questions