gpt4 book ai didi

javascript - 在 JSON 中查找多次出现的特定值

转载 作者:行者123 更新时间:2023-11-30 07:20:12 25 4
gpt4 key购买 nike

我有一个像这样的复杂 JSON:

{
"a": {
"b": {
"c": {
"price": {
"type": "coin",
"value": "currency"
}
}
}
},
"e": {
"f": {
"price": {
"type": "note",
"value": "currency"
}
}
},
"price": {
"type": "cents",
"value": "dollars"
}
}

我正在尝试编写一个 JavaScript 函数,它将在任何位置找到“价格”并提取它的“类型”和“值”。所以我的输出应该是:

"coin" : "currency"
"note" : "currency"
"cents" : "dollars"

最佳答案

您可以使用 for...in 循环创建递归函数以返回对象作为结果。

const data = {"a":{"b":{"c":{"price":{"type":"coin","value":"currency"}}}},"e":{"f":{"price":{"type":"note","value":"currency"}}},"price":{"type":"cents","value":"dollars"}}

function getPrice(data) {
const result = {}
for (let i in data) {
if (typeof data[i] == 'object') Object.assign(result, getPrice(data[i]))
if (i == "price") Object.assign(result, {
[data[i].type]: data[i].value
})
}
return result;
}

const result = getPrice(data);
console.log(result)

关于javascript - 在 JSON 中查找多次出现的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840054/

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