Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Associate Array of Keys with Array of Values Javascript

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!

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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"]]
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!