gpt4 book ai didi

javascript - JS 中迭代对象数组和键值

转载 作者:行者123 更新时间:2023-11-28 19:32:06 24 4
gpt4 key购买 nike

我有一个对象数组

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);
}
}

最佳答案

试试这个:

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
}

}

关于javascript - JS 中迭代对象数组和键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26555326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com