arr = ["billy", "bobby", {"hank": "true"}]
arr.forEach((name, index) => {
if (typeof(name) == "object") {
??????
} else {
console.log(name)
}
})
给定数组arr
,我是否可以使用for each遍历它,以控制台记录每个名称(对于对象,则为键)?我想我可以抛出一个条件来捕获对象,但从那里,我不确定我如何才能注销密钥。
发布于 2018-08-12 02:03:36
您可以迭代通过数组项,并检查该对象,如果是对象,则可以使用循环" for -in“循环对其每个属性进行迭代,该循环接受属性,然后您可以获得属性值
arr = ["billy", "bobby", {"hank": "true"}]
arr.forEach((name, index) => {
if (typeof(name) == "object") {
for(var objProp in name){
console.log(objProp, name[objProp])
}
} else {
console.log(name)
}
})
发布于 2018-08-12 02:03:50
如果对象只包含一个属性,则可以获取Object.keys
的第一项。有关更多信息,您需要迭代键。
var array = ["billy", "bobby", { hank: "true" }];
array.forEach((name, index) => {
if (typeof(name) == "object") {
console.log(Object.keys(name)[0]);
} else {
console.log(name);
}
});
发布于 2018-08-12 02:04:04
使用Object.keys()
函数获取密钥的名称:
const arr = ["billy", "bobby", {"hank": "true"}]
arr.forEach((name, index) => {
if (typeof(name) == "object") {
Object.keys(name).forEach(n => console.log(n)); // log all names in the object
} else {
console.log(name)
}
})
如果您只想注销这些名称,其值为"true"
,请为其添加一个过滤器:
const arr = ["billy", "bobby", {"hank": "true", "connor": "false"}]
arr.forEach((name, index) => {
if (typeof(name) == "object") {
Object.keys(name)
.filter(n => name[n] === "true")
.forEach(n => console.log(n)); // log all names in the object which's value is "true"
} else {
console.log(name)
}
})
https://stackoverflow.com/questions/51802375
复制相似问题