frwebdev
frwebdev

Reputation: 51

How to change [] with {} in my array object

I retrieve this data from an API

{"city":"New York","type":["0","1","9"]}

I need to convert in this way:

{"type":{0:true,1:true,9:true},...}

I try with angular foreach in this way

var tmparr = [];
angular.forEach( $scope.path.type, function (value, key)  {
    tmparr.push(value + ":true")
});
$scope.checkfilters.type = tmparr

but in this way i have this result and it's not what i need

{"business_type":["0:true","1:true","9:true"]} 

I don't know how to replace the [] with {} in my array

If I try to set var tmparr = {} I have undefined error in push function

Upvotes: 0

Views: 197

Answers (3)

Matt Zera
Matt Zera

Reputation: 465

Use bracket syntax

var tmparr = {};
angular.forEach( $scope.path.type, function (value, key)  {
    tmparr[value] = true;
});
$scope.checkfilters.type = tmparr;

Upvotes: 1

Akrion
Akrion

Reputation: 18515

You can also use reduce with an object accumulator:

var data = {"city":"New York","type":["0","1","9"]}

const result = data.type.reduce((r,c) => (r[c] = true, r), {})

console.log(result)

Upvotes: 0

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

You can loop through the type and then copy the values and assign it to true.

var original = {"city":"New York","type":["0","1","9"]};
var copy = {};
for(var i in original.type){
   copy[original.type[i]] = true;
}

console.log(copy);

Upvotes: 0

Related Questions