Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - How to transform a number array to objects array before setState?

I have an array that I am trying to set the value for from a different array however my arrays are not similar the array I am trying to set should look like this expanded = [id1, id2, id3] while the array I am setting from looks more like this

data = [{id: 1, name:"test"},{id:2, name:"test2"},{id:3, name:"test3"}]

not sure how to do this with this.setState


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

const expanded = [1, 2, 3]
const data = expanded.map((e)=>(
  {id: e, name: `test${e-1 ? e : '' }`} 
))

// here you can use setState()
console.log(data);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...