Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - react js lodash loop thru and change a field value

I am new at reactjs and lodash. I have an array of objects which each has many field properties. I want to change a name string value if the boolean property is true. I read thru some of the posts here, seem like .map will loop thru the array

const updatedList = this.props.oldList.map((record) => record.IsTrue === 1 ? `$({record.name} (Updated)` : record.name)

I ran the test and it did not worked at all. Instead of returning list of object with all its properities, I got the following

0: "Test1 (Updated)"
1: "Test2"

There is not object with field names and values. I was expecting the following

[
  {name: "Test1 (Updated)", IsTrue: 1},
  {name: "Test1", IsTrue: 0}
]

Any help with lodash is appreciated.

question from:https://stackoverflow.com/questions/66052902/react-js-lodash-loop-thru-and-change-a-field-value

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

1 Answer

0 votes
by (71.8m points)

You can use spread syntax to return the other key and value and update the name-value where isTrue is 1.

const input = [{ name: "Test1", IsTrue: 1 }, { name: "Test1", IsTrue: 0 }],
    output = input.map((record) => ({ 
      ...record,
      name: record.IsTrue === 1 ? `${record.name} (Updated)` : record.name
    }));
console.log(output);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...