[英]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.如何使用 lodash 将状态数组转换为 Id 和 Name 数组集合。
Is there a way to convert the array in below format ( image shown below):有没有办法将数组转换为以下格式(如下图所示):
You don't really need lodash to do that.你真的不需要 lodash 来做到这一点。
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你对 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. _.each
对数组的每一项执行一个函数。 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
.注意:这也可以通过 JavaScript 的内置.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.无需使用lodash
,只需映射数组并为数组中的每个项目返回一个新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.