gpt4 book ai didi

javascript - 如何使用 ES6 JS/Lodash 选择数组中的特定项并形成新数组

转载 作者:行者123 更新时间:2023-12-03 23:42:23 24 4
gpt4 key购买 nike

例如这是原始数组:

const animals = [{
name: "Lion",
image: "a url",
gender: "male",
age: "2"
},
{
name: "Lion",
image: "a url",
gender: "male",
age: "3"
},
{
name: "Lion",
image: "a url",
gender: "male",
age: "4"
},
{
name: "Lion",
image: "a url",
gender: "male",
age: "6"
},
{
name: "Tiger",
image: "a url",
gender: "male",
age: "6"
},
]

我想形成一个新的数组,它只包含唯一的数据并且只包含名称和图像

所以新数组应该是这样的

const newArray = [{
name: "Lion",
image: "a url"
},
{
name: "Tiger",
image: "a url"
}

]

我如何使用更少的代码,特别是使用 ES6 JS 或使用 lodash 来构建这个 newArray

最佳答案

使用_.uniqBy()得到不同的值,Array#map_.pick()只得到你想要的 Prop :

const animals = [{"name":"Lion","image":"a url","gender":"male","age":"2"},{"name":"Lion","image":"a url","gender":"male","age":"3"},{"name":"Lion","image":"a url","gender":"male","age":"4"},{"name":"Lion","image":"a url","gender":"male","age":"6"},{"name":"Tiger","image":"a url","gender":"male","age":"6"}];

const result = _.uniqBy(animals, 'name').map((o) => _.pick(o, ['name', 'image']));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

关于javascript - 如何使用 ES6 JS/Lodash 选择数组中的特定项并形成新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47111725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com