简体   繁体   中英

Converting flat array to Id and Name object array using Lodash

let states = ["Georgia","California","FL","TX","MA","NJ"];

How do I convert the states array into Id and Name array collection using lodash.

Is there a way to convert the array in below format ( image shown below):

形象

You don't really need lodash to do that.

 let states = ["Georgia","California","FL","TX","MA","NJ"]; let result = states.map((item) => { return { id: item, name: item}}) console.log(result)

You do pretty much the same with lodash

import _ from 'lodash';

result = _.map(states, (item) => {
return {
      id: item,
      name: item}})

 let states = ["Georgia","California","FL","TX","MA","NJ"]; const newObj = []; _.each(states, state => newObj.push({ id: state, name: state })); console.log(newObj);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

_.each performs a function on each item of an Array. With that you can create a new object for each state and push that into a new Array. Note: this could also be accomplished with JavaScript's built in .map .

----- UPDATE ----- Why did I make this complicated many years ago?

 const states = ["Georgia","California","FL","TX","MA","NJ"]; const newObj = states.map(state => ({ id: state, name: state })); console.log(newObj);

No need to use lodash , just map through the array and return a new object for each item in the array.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM