[null, {
"display_with": "7",
"id": "1",
"image": "/images/salt_sugar.png",
"name": "Salt and Sugar",
"subcategories": {
"1": true,
"6": true,
"7": true
}
}, {
"display_with": "6",
"id": "2",
"image": "/images/tea_and_coffee.png",
"name": "Tea and Coffee",
"subcategories": {
"8": true,
"9": true,
"124": true
}
}]
在上面的字符串中,我分别想从第二和第三条记录中分别获得1,6,7和8,9,124。
这是我的逻辑。
recvCategories = JSON STRING
for (var j=0; j<recvCategories.length; ++j){
var category = recvCategories[j];
if (category != undefined){
var subcategories = [];
int size = Object.keys(category.subcategories).length;
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
}
}
如何在//做东西中打印1,6,7和8,9,124?
答案 0 :(得分:2)
假设您的数据名为data
,则应该这样做。
var keys = [];
data.forEach(d => {
if (d.subcategories)
for (var key in d.subcategories)
keys.push(key);
})
看起来很简单但是使用for(var x in y)
实际上会迭代对象的属性并返回propertyNames。
因此,在示例中,我们在数组中调用.forEach()
方法,然后将子类别的每个键push
迭代到一个新数组中。
答案 1 :(得分:1)
类似的东西,
for( i in aList) {
console.log(keys(aList[i] && aList[i].subcategories))
}
// []
// [1, 6, 7]
// [8, 9, 124]
答案 2 :(得分:0)
您的代码中几乎没有指针:
if (category != undefined)
将无法验证null
,代码将依赖object.something
Object.keys(category.subcategories).length;
,subcategories
将会中断。您可以尝试这样的(Object.keys(category.subcategories) || []).length
object.hasOwnProperty
是有意义的,但如果您正在阅读JSON格式,则可以依赖Object.keys
你也可以尝试这样的事情:
function getSubCategoriesKeys(d){
return d.reduce(function(p,c){
if(!isEmpty(c) && typeof(c) === "object" && c.hasOwnProperty("subcategories")){
p = p.concat(Object.keys(c.subcategories))
}
return p;
}, [])
}
function isEmpty(o){
return o === undefined || o === null || o.toString().trim().length === 0
}
var data = [null, {
"display_with": "7",
"id": "1",
"image": "/images/salt_sugar.png",
"name": "Salt and Sugar",
"subcategories": {
"1": true,
"6": true,
"7": true
}
}, {
"display_with": "6",
"id": "2",
"image": "/images/tea_and_coffee.png",
"name": "Tea and Coffee",
"subcategories": {
"8": true,
"9": true,
"124": true
}
}]
var keys = getSubCategoriesKeys(data);
console.log(keys)