gpt4 book ai didi

javascript - 从键中检索值数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:26 26 4
gpt4 key购买 nike

我正在尝试遍历我拥有的 JSON 对象,以检索元素列表。

我正在筛选的 JSON 代码非常复杂,但这里是一小段代码。它基本上显示了我正在寻找的内容。

{
"ProductsList": [
{
"ProductInfo": {
"Brand": "LG",
"p_product_barcode": "048231014731",
"p_product_bullets_json": {
"Value": [
"4.3 cubic foot ",
"Recognized",
"Customize your washer",
"6Motion Technology ",
"Troubleshoot quickly",
"meow",
"who",
"special"
]
}
}]
}

我正在尝试从“p_product_bullets_json”中的“Value”获取值列表。我想得到所有的元素。

到目前为止我有这个,但我得到的只是一个空列表。

function getLists(obj, key) {

// Empty object array
var objects = [];

// Searches through the JSON code to find the given key
for (var k in obj) {

// If there are still leafs left, then keep searching
if (!obj.hasOwnProperty(k)) continue;

// If the leaf doesn't match the key, try again (recursion)
if (typeof obj[k] == 'object') {

objects = objects.concat(getValues(obj[k], key));

// If the leaf does match the key, then push that value onto the array
} else if (k == key) {

$.each(obj[k], function(i, val) {

console.log('Key: ' + i + ' Val: ' + val)

});
}
}

return objects;
}

我只是查看“值”的每个键,但这个名称不是唯一的,在其他地方还有其他具有相同名称的键。

如有帮助,将不胜感激,谢谢!

最佳答案

你需要有一种情况,你从那个函数返回一个数组,试试这个:

var input = {
"ProductsList": [
{
"ProductInfo": {
"Brand": "LG",
"p_product_barcode": "048231014731",
"p_product_bullets_json": {
"Value": [
"4.3 cubic foot ",
"Recognized",
"Customize your washer",
"6Motion Technology ",
"Troubleshoot quickly",
"meow",
"who",
"special"
]
}
}
}]
};
function getLists(obj, key) {

var objects = [];

for (var k in obj) {

if (!obj.hasOwnProperty(k)) continue;
if (k == key) {
if (obj[key] instanceof Array) {
return obj[key]
}
} else if (typeof obj[k] == 'object') {

objects = objects.concat(getLists(obj[k], key));
}
}

return objects;
}
document.getElementsByTagName('div')[0].innerHTML = JSON.stringify(getLists(input, 'Value'));
<div></div>

关于javascript - 从键中检索值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609233/

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