【发布时间】:2020-10-26 18:53:01
【问题描述】:
我有一个如下所示的对象 {key: id numbers}
var obj = {
"c4ecb": {id: [3]},
"a4269": {id: [34,36]},
"d76fa": {id: [54,55,60,61]},
"58cb5": {id: [67]}
}
如何在下面的数组中循环 id 以上的每个,并返回 label?
var response =
{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}
最后,我要做的是查找键并返回一串 id 值。
例如输入c4ecb,输出strawberry。输入a4269,输出lettuce, radish。输入d76fa,输出“spaghetti, rigatoni, lasagna, fettuccine”
我认为将多个标签输出连接到一个字符串中,我可以使用类似的东西
array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();
所以最后我想拥有类似的东西
var fruits = [some code that outputs "strawberry"];
var vegetables = [some code that outputs "lettuce, radish"];
var pasta = [some code that outputs "spaghetti, rigatoni, lasagna, fettuccine"];
到目前为止我已经尝试过:
仅当需要调用一个 id 时,以下循环才会返回 id:例如仅在{id: 3}的情况下,但在{id: 34,36}之类的情况下返回null(因为它在id中寻找'34,36',它不存在-我需要单独查找每一个。
response.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
【问题讨论】:
-
您的
obj不是有效的 JSON。我认为这是问题的一部分,但也许我误解了谷歌应用程序脚本。我本来想说你应该.split(",")ID 并为你找到的每一个做一个查找。 -
"a4269": {id: 34,36},//if id is a string then "id":"34,36" if it is an array then it should be "id":[34,36] -
我确实将 ids 更改为上面的数组。所以现在不是“id”:“34,36”,而是“id”:[34,36]。然后我需要返回一个像 [{"a4269": {label: [lettuce, radish]}}, {"d76fa": {label: [spaghetti, rigatoni, lasagna, fettucine]}}, ...] 这样的数组我需要 var vegetables = return 'lettuce, radish',然后 var Pasta = return 'spaghetti, rigatoni, lasagna, fetuccine' 等,我不知道如何处理
标签: javascript arrays google-apps-script