gpt4 book ai didi

Javascript array.find() 仅在第一个实例中找到

转载 作者:行者123 更新时间:2023-11-29 21:14:58 25 4
gpt4 key购买 nike

我有以下对象数组:

var data = {};

data.type = {
"types": [{
"testA": {
"testVar": "abc",
"testContent": "contentA"
}
}, {
"testB": {
"testVar": "def",
"testContent": "contentB"
}
}]
};

我想做的是通过搜索它的父级和兄弟级找到它所属的对象来找到 testContent 的值:

/* within the data, find content where parent is testA and sibling testVar is "abc" */
var findSet = data.type.types.find(function(entry) {
return entry['testA'].testVar === "abc";
});

console.log(findSet['testA'].testContent); /* returns string "contentA" as expected */

这对第一个对象工作正常但找不到下一个对象,给出错误:

Cannot read property 'testVar' of undefined

var findSet = data.type.types.find(function(entry) {
return entry['testB'].testVar === "def"; /* Cannot read property 'testVar' of undefined */
});

console.log(findSet['testB'].testContent);

我还能如何找到需要的东西?

Here's a fiddle to test the output

最佳答案

var data = {};

data.type = {
"types": [{
"testA": {
"testVar": "abc",
"testContent": "contentA"
}
}, {
"testB": {
"testVar": "def",
"testContent": "contentB"
}
}]
};

var findSet = data.type.types.find(function(entry) {
return entry['testA'] && entry['testA'].testVar === "abc";
});

console.log(findSet['testA'].testContent);

var findSet = data.type.types.find(function(entry) {
return entry['testB'] && entry['testB'].testVar === "def"; /* Cannot read property 'testVar' of undefined */
});

console.log(findSet['testB'].testContent);

在测试他的属性之前,先检查你的条目是否存在。

关于Javascript array.find() 仅在第一个实例中找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39828921/

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