我有一个对象数组
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
我想检查对象属性并执行某种逻辑。我是JS的新手,所以我不确定我可以访问的所有方法。基本上我想将对象的键值与字符串进行比较。如果键和字符串相同,那么我将从数组中删除该对象。我不确定如何遍历数组中对象的键。
var str = "v1";
for (var i in j) {
if (i.key == str) { // not sure how to access key value
j.splice(i,1);
}
}
答案 0 :(得分:2)
试试这个:
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
for (var i = 0; i < j.length; i++)
{
for (var k in j[i]) //do use this if you need to iterate
{
if (k === "mySomething")
{
//...do your stuff
}
}
}
修改强>
少详细:
for (var i = 0; i < j.length; i++)
{
if ("mySomething" in j[i])
{
//...do your stuff
}
}
答案 1 :(得分:1)
正如我们在评论中讨论的那样,很少有理由使用每个只有一个属性的对象数组(除非你使用数组来维护特定的顺序),所以我想也许你的问题如果数据结构如下可能会更容易:
var j = {"v1":["1","2","3"], "v2":["4","5","6"], "v3":["7","8","9"]};
然后,您可以像这样迭代它:
for (var key in j) {
console.log("j[" + key + "] = ", j[key]);
}