我有对象:
[Object]
0: {Class: "MTH 1100-A", __rowNum__: 1}
1: {Class: "CSC 3200-B", __rowNum__: 2}
2: {Class: "ART 4334-E", __rowNum__: 3}
3: {Class: "REC 3223-C", __rowNum__: 4}
在我这样做之前,我想把所有这些都放到一个数组中,虽然我只是在尝试打印它们,但我似乎无法做到这一点。这是我的代码:
const obj = {
0: { Class: "MTH 1100-A",__rowNum__: 1},
1: { Class: "CSC 3200-B", __rowNum__: 2 },
2: { Class: "ART 4334-E", _rowNum__: 3 } ,
3: { Class: "REC 3223-C", _rowNum__: 4 }
};
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while (arr.length && (obj = obj[arr.shift()]));
return obj;
}
console.log(getDescendantProp(obj, '0.Class'));
for (var i = 0; i < obj.length; i++) {
console.log(getDescendantProp(obj, "\'" + i + ".Class\'"));
}
对于输出,你得到:
“MTH 1100-A”
未定义
未定义
未定义
未定义
那么为什么我不能得到那些价值.....?
答案 0 :(得分:0)
您的代码存在一些问题。
getDescendantProp(obj, i + ".Class")
。无需逃避报价。我修改了一下你的代码以便它可以工作并添加了一些变量来跟踪发生了什么:
var obj = {
0: {Class: "MTH 1100-A", __rowNum__: 1},
1: {Class: "CSC 3200-B", __rowNum__: 2},
2: {Class: "ART 4334-E", __rowNum__: 3},
3: {Class: "REC 3223-C", __rowNum__: 4}
}
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
var arrCopy = arr.slice();
arrCopy = arrCopy.shift();
while(arr.length && (obj = obj[arr.shift()])){
var bla = "bla";
};
return obj;
}
for(var i = 0; i< Object.keys(obj).length; i++) {
var o = getDescendantProp(obj, i + ".Class");
console.log(o);
}
但是,请注意,您可以像obj.property或obj [&#34; property&#34;]一样访问对象属性。考虑到这一点,可以进一步简化为以下内容:
var descendantsArray = []; // Array to put each desired element from obj
var objKeys = Object.keys(obj); // Array with the keys to the object
for (var i = 0; i < objKeys.length; i++) {
var currentKey = objKeys[i]; // Get current key
var currentElement = obj[currentKey]; // Get the element that corresponds to the key
descendantsArray.push(currentElement.Class); // Add the current element's Class property to the Array
console.log(currentElement.Class); // Print the 'Class' property of the current element
}
干杯
答案 1 :(得分:0)
对象没有length
属性。所以你循环虽然未定义了值。
您可以将对象转换为Object.values(obj)
的数组:
const obj = {
0: { Class: "MTH 1100-A",__rowNum__: 1},
1: { Class: "CSC 3200-B", __rowNum__: 2 },
2: { Class: "ART 4334-E", _rowNum__: 3 } ,
3: { Class: "REC 3223-C", _rowNum__: 4 }
};
function getDescendantProp(obj, key) {
return Object.values(obj).map(i => i[key]);
}
console.log(getDescendantProp(obj, 'Class'));
const arr = getDescendantProp(obj, 'Class');
arr.forEach(i => {
console.log(i);
});
&#13;
答案 2 :(得分:0)
我找到了答案,一个小的语法错误,我不明白,但这里是问题:
在
for (var i = 0; i < obj.length; i++) {
console.log(getDescendantProp(obj, "\'" + i + ".Class\'"));
}
在
for (var i = 0; i < obj.length; i++) {
console.log(getDescendantProp(obj, i+`.Class`));
}