let array = [ { name: 111, id: 1 }, { name: 222, id: 2 }, { name: 111, id: 3 }, { name: 111, id: 4 }, { name: 222, id: 5 }, ] let bb = [ { name: 111, id: [1, 3, 4] }, { name: 222, id: [2.5] }, ]将array的数组转化为bb的数组
时间: 2024-02-24 10:57:26 浏览: 23
可以使用 JavaScript 中的 reduce 方法来实现这个功能。具体实现代码如下:
```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) => {
let obj = acc.find(item => item.name === cur.name);
if (!obj) {
obj = { name: cur.name, id: [] };
acc.push(obj);
}
obj.id.push(cur.id);
return acc;
}, []);
console.log(result);
```
首先使用 reduce 方法将数组中的对象按照 name 属性进行分类,将相同 name 的对象的 id 构成的数组放在同一个对象中。最终得到的 result 数组中的对象的 name 属性与 bb 数组中的对象相同,id 属性是相同 name 对象的 id 构成的数组。
相关问题
let array = [ { name: 111, id: 1 }, { name: 222, id: 2 }, { name: 111, id: 3 }, { name: 111, id: 4 }, { name: 222, id: 5 }, ] 取出name一致,中的id
可以使用 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()` 方法会遍历数组中的每个元素,并返回一个新的数组,新数组中的每个元素都是回调函数的返回值。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)