-1

I have one array of keys that I want to associate with all of the data returned from the API:

        const arr = [
          'cat',
          'dog',
          'horse',
        ]

const data_from_api = [
            ["cat_1",
            "dog_1",
            "horse_1"],

            ["cat_2",
            "dog_2",
            "horse_2"],
]

I want to create objects with the data that the keys area the values of this array and the values are the data that come from the API. How could I do this? Thanks in advance!

1
  • Should the mapping be done by array-index? Does cat_1 belong to cat, because it has index [0] in your and the api's arrays? Commented Jul 16, 2022 at 16:13

1 Answer 1

-1

You could iterate over the api-data like this:

const arr = 
  ['cat',  'dog',  'horse',]
const data_from_api = [
  ['cat_1','dog_1','horse_1'],
  ['cat_2','dog_2','horse_2'],
]

const result = {}
data_from_api.forEach((api, i) =>

  // find array item (or create one, if not yet existant)
  (result[arr[i]] || (result[arr[i]] = []))

  // add current item
  .push(data_from_api[i])
)
console.log(result);

The result would be:

{
  cat: [["cat_1", "dog_1", "horse_1"]],
  dog: [["cat_2", "dog_2", "horse_2"]]
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.