Home > OS >  How to extract object from arrayList and add into another arrayList
How to extract object from arrayList and add into another arrayList

Time:03-03

I am trying to convert one arraylist to another by modifying one of the objects inside

   let array1 = [
            {
              name: "test",
              address: "testaddress",
              state: {
                2022: {
                  January: { month_state: "pending" },
                },
              },
            },
            {
              name: "test2",
              address: "testaddress2",
              state: {
                2022: {
                  January: { month_state: "pending" },
                },
              },
            },
          ];

And I want to convert into this, which is the correct way? Thanks.

let array2 = [
            {
              name: "test",
              address: "testaddress",
              2022: {
                January: { month_state: "pending" },
              },
            },

            {
              name: "test2",
              address: "testaddress2",
              2022: {
                January: { month_state: "pending" },
              },
            },
          ];

CodePudding user response:

let array2 = array1.map(({ state, ...rest }) => ({ ...rest, ...state }))

This code will do.

CodePudding user response:

There are several ways to achieve what you're asking.

I'll show you using the functional approach with .map

let array1 = [
    {
        name: "test",
        address: "testaddress",
        state: {
            2022: {
                January: { month_state: "pending" }
            }
        }
    },
    {
        name: "test2",
        address: "testaddress2",
        state: {
            2022: {
                January: { month_state: "pending" }
            }
        }
    }
];

let array2 = array1.map((el) => {
    const tmp = {
        name: el.name,
        adress: el.adress
    };
    
    // Here we iterate el.state, so we can extract each year.
    /* We need to dynamically generate a property name (each year). 
So we use a feature called "computed property names (ES2015)" */
    for (const prop in el.state) {
        tmp[prop] = el.state[prop];
    }

    return tmp;
});
console.log(array2);

You could also use a for loop, wich is also a valid approach.

  • Related