Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate through nested Objects and combine key and value?

const products = {
  value: {
    phone: [],
    lamp: [],
    car: ["bmw", "toyota", "audi"]
  }
};

In the given object I want to iterate and get keys.
Note that values are array of strings.

I’d like to get all keys and if values are not empty arrays I want to combine with keys and return an array with this structure

   [
    phone,
    lamp,
    car-bmw,
    car-toyota,
    car-audi
  ]

Here is what I did so far, which is not what I want

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const products = {
  value: {
    phone: [],
    lamp: [],
    car: ["bmw", "toyota", "audi"]
  }
};

const mappedProducts = Object.entries(products.value).map(([value, items]) => {
  //console.log("value :", value, "items :", items)
  if (items.length > 0) {
    return {
      car: items.map((c) => c)
    };
  }
});

console.log(mappedProducts);

Any help will be appreciated.

>Solution :

I modified what you did a bit, you can you flatMap

const products = {
  value: {
    phone: [],
    lamp: [],
    car: ["bmw", "toyota", "audi"]
  }
};

const mappedProducts = Object.entries(products.value).flatMap(([value, items]) => {
  //console.log("value :", value, "items :", items)
  if (items.length > 0) {
    return items.map(item => `${value}-${item}`);
  } else {
    return [value];
  }
});

console.log(mappedProducts);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading