![](/img/trans.png)
[英]How to add to each object in an array a key-pair value based on each objects id?
[英]How to add each key pair from this Object into an Array as new Objects?
http://codepen.io/leongaban/pen/xwwdXr?editors=101
我有一個API,它返回的對象看起來像這樣:
{ unsure: 5, products: 25, trend: 124 }
我需要做的是將這些鍵/值對添加到數組中,以便它們像這樣出來:
catArray = [
{ unsure: 5 },
{ products: 5 },
{ trend: 5 },
]
更好的是:
catArray = [
{
name: unsure,
count: 5
},
{
name: products,
count: 15
},
{
name: trend,
count: 50
}
]
當前的代碼筆代碼:
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);
現在,我要返回一個長度為0
奇怪數組,我的目標是一個包含對象的數組,然后可以使用這些對象迭代並在Angular應用程序中使用ng-repeat
建立一個列表。
非常接近,您可以執行以下操作:
var data = { unsure: 5, products: 25, trend: 124 }
var newData = [];
for (var key in data) {
newData.push({
name: key,
count: data[key]
});
}
或者,另一種方法
var newData = Object.keys(data).map(function(key) {
return {
name: key,
count: data[key]
}
});
演示: http : //jsfiddle.net/gnrchtvj/
你可以用這種方式
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.