0

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

3 Answers 3

1

Use bracket syntax

var tmparr = {};
angular.forEach( $scope.path.type, function (value, key)  {
    tmparr[value] = true;
});
$scope.checkfilters.type = tmparr;
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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)

Comments

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.