0

I have an object that looks like the following {key: id numbers}

var obj = {
  "c4ecb": {id: [3]},
  "a4269": {id: [34,36]},
  "d76fa": {id: [54,55,60,61]},
  "58cb5": {id: [67]}
}

How do I loop each above id in the following array, and return the 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
            }
          ],
        }
      ]
    }

Finally, what I want to do is look up the key and return a string of id values. For example, input c4ecb and output strawberry. Input a4269 and output lettuce, radish. Input d76fa and output "spaghetti, rigatoni, lasagna, fettuccine"

I think to join the multiple labels output into one string I could use something like

array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();

So in the end I want to have something like

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"];

What I've tried so far: The following loop will return the id only if there is one id to be called for: e.g. only in case one where {id: 3} but returns null in cases like {id: 34,36} (because it's looking for '34,36' in id, which doesn't exist - I need to look for each one individually.

response.data.forEach(({key, options}) => {
  if (obj[key]) {
    options.forEach(({id, label}) => {
      if (id == obj[key].id) obj[key].label = label;
    });
  }
});
console.log(obj)
3
  • Your obj is not valid JSON. I assume that's part of the problem, but maybe I misunderstand google apps script. I was going to say you should .split(",") the IDs and do a lookup for each that you find. Commented Oct 26, 2020 at 19:00
  • "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] Commented Oct 26, 2020 at 20:44
  • I did change the ids to an array above. so instead of "id": "34,36" it's now "id": [34,36]. Then I need to return an array like [{"a4269": {label: [lettuce, radish]}}, {"d76fa": {label: [spaghetti, rigatoni, lasagna, fettuccine]}}, ...] then I need have var vegetables = return 'lettuce, radish', then var pasta = return 'spaghetti, rigatoni, lasagna, fetuccine' etc, which I don't know how to approach Commented Oct 26, 2020 at 21:17

1 Answer 1

2

Filter the response object to focus on the category that matches the id. Map over the options array and select the items which appear in obj[id]. Finally convert the filtered results to a string.

See filteredLabelsAsString() function below for implementation.

var obj = {
  "c4ecb": {"id": [3]},
  "a4269": {"id": [34,36]},
  "d76fa": {"id": [54,55,60,61]},
  "58cb5": {"id": [67]}
}

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
            }
          ],
        }
      ]
    }];
 
 
 function filteredLabelsAsString(obj_key, obj, content=response) {
    // sanity check: obj must contain obj_key
    if (Object.keys(obj).includes(obj_key)) {
        return content.filter((item) => {
            // filter content using value of obj_key
            return item.data[0].key == obj_key;
        }).map((item) => {
            // item : { success: true, data: [] }
            // map over options array
            return item.data[0].options.map((opt) => {
                // option : {id, label}
                // return the label if the id is in the obj object's list
                if (obj[item.data[0].key].id.includes(opt.id))
                    return opt.label;
            }).filter((label) => {
                // filter out empty items
                return label !== undefined;
            });
        }).join(",");
    }
    // if obj does not contain obj_key return empty string
    return "";
}

console.log("fruits: " + filteredLabelsAsString("c4ecb", obj));

console.log("vegetables: " + filteredLabelsAsString("a4269", obj));

console.log("pasta: " + filteredLabelsAsString("d76fa", obj));

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the above filter. I can run the code snippet and see the results log perfectly. When I paste this into google apps script, however, I'm getting an error: Cannot convert undefined or null to object (line 94), which is if Object.keys(obj).includes(obj_key)) { I don't know why it's coming up as null. I'm not sure if the content = response is referencing the above response variable correctly that's why it's returning null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.