使用Lodash将平面数组转换为Id和Name对象数组

时间:2017-09-21 19:57:42

标签: javascript typescript lodash

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

如何使用lodash将states数组转换为Id和Name数组集合。

有没有办法以下面的格式转换数组(图片如下所示):

image

2 个答案:

答案 0 :(得分:4)

你真的不需要lodash这样做。



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

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




你和lodash

几乎一样
import _ from 'lodash';

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

答案 1 :(得分:1)



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>
&#13;
&#13;
&#13;

_.each对数组的每个项执行一个函数。有了它,您可以为每个状态创建一个新对象,并将其推送到一个新的数组。注意:这也可以通过内置.map

的JavaScript来实现