1

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" },
              },
            },
          ];

2 Answers 2

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

This code will do.

Sign up to request clarification or add additional context in comments.

2 Comments

@Shawn Like this: map, i.e. map in square brackets and the link in parentheses.
If you're not sure how or why this works, have a look at the docs for the map function, the spread syntax, rest parameters and arrow function expressions.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.