0

How do I create a new array from another array

my array is data1

this.state = {
    data1: [
        {'x':'%20', 'y':11, 'z':'sunday'},
        {'x':'%30', 'y':21, 'z':'monday'},
        {'x':'%40', 'y':31, 'z':'tuesday'}          
    ],
    data2: [],
}

and i want to create data2, that look like this

data2: [
    {'x':'%20-(11)-sunday'},
    {'x':'%30-(21)-monday'},
    {'x':'%40-(31)-tuesday'}
]

3 Answers 3

1

Have a look at array.map.

const data2 = data1.map(value => ({ x: `${value.x}-(${value.y})-${value.z}` }))
Sign up to request clarification or add additional context in comments.

Comments

0

  data1=  [
   {'x':'%20', 'y':11, 'z':'sunday'},
   {'x':'%30', 'y':21, 'z':'monday'},
   {'x':'%40', 'y':31, 'z':'tuesday'}          
  ]
    
  data2 = data1.map((item)=> ({x: Object.values(item).join('-')}))
  console.log("data2", data2)

Comments

0

You can use below function to convert data1 array to data2 array:

createCustomArray() {
   this.state.data1.forEach(function (item) {
      this.state.data2.push({'x': item.x+'-('+item.y+')-'+item.z});
   });
}

2 Comments

This is agains the guidelines. You are mutating the state this wont rerun the component lifecycle.
As @OzgrMan is referring the data2 array within state, its essential to append data to data2 array within state. Hence it is a good practice to create a custom array whenever you get data1 by just calling that function

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.