Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - How do I rebuild an array of objects in an array

I have a array of objects that contain array of objects. I would like to know how I can browse it. I tried with a map but the parent data doesn't come up...

My result:

 let cars = [{   name: 'Volvo',   equipments:
         [{
           name: 'saddleries',
           options:[array],
         }]
       }];

I would like this result :

 let cars = [{   name: 'Volvo (1) equipment',   equipments:
     [{
       name: 'saddleries (2) options',
       options:
         [{name: 'leather'},
           {name: 'fabrics'},
     }], }]

Does anyone have a solution?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It sounds like you just want to create a new array where the name contains the length of equipments or options. Try this:

const cars = [
  {
    name: "Volvo",
    equipments: [
      {
        name: "saddleries",
        options: [{ name: "leather" }, { name: "fabrics" }],
      },
    ],
  },
];

const newCars = cars.map(({ name, equipments }) => ({
  name: `${name} (${equipments.length}) equipment`,
  equipments: equipments.map(({ name, options }) => ({
    name: `${name} (${options.length}) options`,
    options,
  })),
}));

console.log(newCars);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...