Is there an easy way in lodash to take this:
const sampleSource = [
"String 1",
"String 2",
]
And get this:
[
{id: "String 1", text: "String 1"},
{id: "String 2", text: "String 2"},
]
I need to format it like this to pass into a 3rd party react component. I've played with .map and .zipObject a bit but havent been able to get it right.
I thought something like this should work:
_.chain(sampleSource).map(s => ({ id: s, text: s })).value()
But it gives me:
[
{
id: ["String 1", "String 2"],
text: ["String 1", "String 2"],
}
]
Something like this. Added chain example.
const sampleSource = [ "String 1", "String 2", ] let result = _.map(sampleSource, function(item) { return {id: item, text: item}; }); console.log(result); let result2 = _.chain(sampleSource).map(function(item) { return {id: item, text: item}; }); console.log(result2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
You don't need lodash for this, ordinary JavaScript .map()
should work.
const sampleSource = [ "String 1", "String 2", ]; const result = sampleSource.map(s => ({id: s, text: s})); console.log(result);
There is a method in lodash
named keyBy .
You can use it like this
const sampleSource = [ "String 1", "String 2", ]; const result = _.keyBy(sampleSource); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.