Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

50
Views
How do I populate an array of objects where every object has an array inside of it using response from rest API?

I can't google the right solution for this for about an hour straight, So I'm getting a response from the API that looks like this:

[
  {
    "Name": "name1",
    "Title": "Name One",
    "Children": [
      {
        "Name": "Name 1.1",
        "Title": "Name one point one"
      },
     ]

And I need it to fit this kind of "mold" for the data to fit in:

{
title: 'Name One',
value: 'name1',
key: '1',
children: [
  {
    title: 'Name one point one',
    value: 'Name 1.1',
    key: 'key1',
  },

I am trying to achieve this using a foreach but It's not working as intended because I need to do this all in one instance of a foreach. Here's what I gave a go to(vue2):

   created() {
    getData().then(response => {
      const formattedResponse = []
      response.forEach((el, key) => {
        formattedResponse.title = response.Title
        formattedResponse.name = response.Name
        formattedResponse.children = response.Children
      })
    })
7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

Use map over the main array and use destructuring assignment to extract the properties by key, and relabel them, and then do exactly the same with the children array. Then return the updated array of objects.

const data=[{Name:"name1",Title:"Name One",Children:[{Name:"Name 1.1",Title:"Name one point one"}]},{Name:"name2",Title:"Name Two",Children:[{Name:"Name 1.2",Title:"Name one point two"}]}];

const result = data.map((obj, key) => {

  const { Title: title, Name: value } = obj;
  
  const children = obj.Children.map(obj => {
    const { Title: title, Name: value } = obj;
    return { title, value, key: (key + 1).toString() };
  });
  
  return { title, value, children };
   
});

console.log(result);

7 months ago · Juan Pablo Isaza Report

0

Your API response is JSON. All you need to do is:

var resp=JSON.parse(API response);
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs