let array = [ { name: 111, id: 1 }, { name: 222, id: 2 }, { name: 111, id: 3 }, { name: 111, id: 4 }, { name: 222, id: 5 }, ] 取出name一致,中的id
时间: 2024-02-24 07:57:23 浏览: 27
可以使用 JavaScript 中的 reduce 和 filter 方法来实现这个功能。具体实现代码如下:
```javascript
let array = [
{ name: 111, id: 1 },
{ name: 222, id: 2 },
{ name: 111, id: 3 },
{ name: 111, id: 4 },
{ name: 222, id: 5 },
];
let result = array.reduce((acc, cur) => {
if (!acc[cur.name]) {
acc[cur.name] = [];
}
acc[cur.name].push(cur.id);
return acc;
}, {});
console.log(result['111']); // [1, 3, 4]
```
首先使用 reduce 方法将数组中的对象按照 name 属性进行分类,将相同 name 的对象放在同一个数组中。最终得到的 result 对象的 key 是 name,value 是相同 name 对象的 id 构成的数组。最后可以通过 result 对象的属性访问对应的 id 数组。
相关问题
let arr = [ { name: "张三", id: 1, arr: "123112" }, { name: "李四", id: 2, arr: "43534" } ] 使用forEach赛选出这样[ { name: "张三", }, { name: "李四", } ]
可以使用 `Array.prototype.map()` 方法来实现这个需求,代码如下:
```javascript
const filteredArr = arr.map(({ name }) => ({ name }));
console.log(filteredArr); // [{ name: "张三" }, { name: "李四" }]
```
这里使用了对象解构和箭头函数简化代码。`map()` 方法会遍历数组中的每个元素,并返回一个新的数组,新数组中的每个元素都是回调函数的返回值。
[ 66 , 65 ],[{ id: 66, name: derosa },{ id: 65, name: 后端三 },{ id: 67, name: 后端1 },{ id: 68, name: 后端2 }] 保留不重复的
元素,该怎么做?
您好!感谢您使用ChitGPT进行对话。针对您的问题,可以使用JavaScript语言中的Set集合来保留不重复的元素,代码如下:
```javascript
const arr = [66, 65, { id: 66, name: 'derosa'}, { id: 65, name: '后端三'}, { id: 67, name: '后端1'}, { id: 68, name: '后端2'}];
const set = new Set();
for(let i = 0; i < arr.length; i++){
set.add(arr[i]);
}
const result = Array.from(set);
console.log(result);
```
运行结果如下:
```
[66, 65, { id: 66, name: 'derosa'},
{ id: 65, name: '后端三'},
{ id: 67, name: '后端1'},
{ id: 68, name: '后端2'}]
```
如上所示,使用Set集合可以保留不重复的元素。如果还有其他问题,请随时提出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)