Leon Gaban
Leon Gaban

Reputation: 39018

How to add each key pair from this Object into an Array as new Objects?

http://codepen.io/leongaban/pen/xwwdXr?editors=101

I have an API that returns an Object that looks like this:

{ unsure: 5, products: 25, trend: 124 }

What I need to do is take those key/value pairs and add those into an Array so they come out like so:

catArray = [
    { unsure: 5 },
    { products: 5 },
    { trend: 5 },
]

And better yet:

catArray = [
    {
        name: unsure,
        count: 5
    },
    {
        name: products,
        count: 15
    },
    {
        name: trend,
        count: 50
    }
]

Current codepen code:

var categories = { unsure: 5, products: 25, trend: 124 }
var catArray   = [];

for (var i in categories) {
  console.log(i + ":" + categories[i]);
  catArray[i] = categories[i];
}

// vm.categories = Object.keys(data.data.categories);
console.log('catArray =',catArray);

At the moment I'm getting back some strange Array with a length of 0, my goal is an Array that has objects with which I can then iterate and build out a list with ng-repeat in my Angular app.

enter image description here

Upvotes: 0

Views: 45

Answers (2)

tymeJV
tymeJV

Reputation: 104775

Pretty close, you can do:

var data = { unsure: 5, products: 25, trend: 124 }
var newData = [];

for (var key in data) {
    newData.push({
        name: key,
        count: data[key]
    });
}

Or, a different approach

var newData = Object.keys(data).map(function(key) {
    return {
        name: key,
        count: data[key]
    }
});

Demo: http://jsfiddle.net/gnrchtvj/

Upvotes: 5

Joy Biswas
Joy Biswas

Reputation: 6527

You can use this way

var categories = { unsure: 5, products: 25, trend: 124 }
var catArray   = [];
for (var i in categories) {
  if (categories.hasOwnProperty(i)) {
    alert(i + " -> " + categories[i]);
    catArray.push({name:i,value:categories[i]});
  }
}


// vm.categories = Object.keys(data.data.categories);
console.log(catArray);

Upvotes: 1

Related Questions