Home > OS >  Angular - Map Object array value to same key
Angular - Map Object array value to same key

Time:11-28

I have an object like this,

const product = {
  name: 'watch',
  color: ['brown', 'white']
}

Expected result:

I need to flatten this object to below object format,

name: 'watch'
color: 'brown'
color: 'white'

To iterate the product object, I have to use another inner for-loop like below. Before iterating this outer for-loop, I need to flatten the input product object like above expected result. So that I can avoid the additional inner for loop to iterate the array values. How to simplify this?

    for (const [key, val] of Object.entries(product)) {
      if (Array.isArray(val)) {
        if (val.length) {
          for (const v of val) {
            console.log('Array val key:'   key   ', val:'   v);
          }
        }
      } else {
        console.log('key:'   key   ', val:'   val);
      };
    }

My tsconfig.json target is es2015(es6) and lib has es2017(es8) and es2018(es9). es10 and above features are not supported.

I saw Dennis Ameling answer here One liner to flatten nested object which is somewhat identical to my requirement, but I don't need the array key to be appended to the parent object.

Why I need to flatten this array value to same key?

I have to push these key value to another array like,

let data = [];
this.data.push(`productkey${index}=${key}_productval${index}=${val}`);

I will push in this format to data array,

 productkey0=name_productval0=watch,
 productkey1=color_productval1=brown,
 productkey2=color_productval2=white,

Now with above for loop I have to use push method in outer for loop and inner loop. I want to simplify this.

CodePudding user response:

I want to shorten the loop iteration code, so that I can avoid the additional inner for loop to iterate the array values

This is not possible. You have a nested data structure, you will need nested loops to process it.

However, you can drop the superfluous val.length check, the loop body already won't run if the array is empty.

for (const [key, val] of Object.entries(product)) {
  if (Array.isArray(val)) {
    for (const [i, v] of val.entries()) {
      console.log('Array val key:'   key   '[' i '], val:'   v);
    }
  } else {
    console.log('key:'   key   ', val:'   val);
  };
}
  • Related