{ name: "tony", id: "1", age: "20" },
{ name: "jack", id: "2", age: "21" },
{ name: "tony", id: "3", age: "50" },
{ name: "jack", id: "4", age: "10" },
{ name: "mark", id: "5", age: "22" },
{ name: "mark", id: "6", age: "40" }
要将数据中name相同的项合并成一个对象(如下):
afterData: [
{name: "tony",origin: [{ name: "tony", id: "1", age: "20" },{ name: "tony", id: "3", age: "50" }]},
{name: "jack",origin: [{ name: "jack", id: "2", age: "21" },{ name: "jack", id: "4", age: "10" }]},
{name: "mark",origin: [{ name: "mark", id: "5", age: "22" },{ name: "mark", id: "6", age: "40" }]}
实现方式很简单,记下来方便下次使用
let tempArr = [];
for (let i = 0; i < this.beforeData.length; i++) {
if (tempArr.indexOf(this.beforeData[i].name) === -1) {
this.afterData.push({
name: this.beforeData[i].name,
origin: [this.beforeData[i]]
tempArr.push(this.beforeData[i].name);
} else {
for (let j = 0; j < this.afterData.length; j++) {
if (this.afterData[j].name == this.beforeData[i].name) {
this.afterData[j].origin.push(this.beforeData[i]);
break;
不知道大家在开发过程中有没有遇到这样的数据转换:数据源是这样的beforeData: [ { name: "tony", id: "1", age: "20" }, { name: "jack", id: "2", age: "21" }, { name: "tony", id: "3", age: "50" }, { na...
var arr = [
{"id":"1001","name":"值1","value":"111"},
{"id":"1001","name":"值1","value":"11111"},
{"id":"1002","name":"值2","value":"25462"},
{"id":"1002"...
1. 遍历数组,对于每个元素,获取需要归类的属性值。
2. 在 reduce() 方法中创建一个对象,用于保存归类后的结果。
3. 对于每个元素,检查对象中是否已经存在该属性值对应的数组,如果不存在,则创建一个新数组,并将该元素添加到数组中;如果已经存在,则将该元素添加到对应的数组中。
4. 最后,将对象中的值转换为数组,即可得到归类后的结果。
下面是一个示例代码:
```javascript
const arr = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'orange', type: 'fruit' },
{ name: 'broccoli', type: 'vegetable' },
{ name: 'pear', type: 'fruit' },
{ name: 'tomato', type: 'vegetable' },
{ name: 'pepper', type: 'vegetable' },
{ name: 'grape', type: 'fruit' },
{ name: 'potato', type: 'vegetable' },
const result = arr.reduce((obj, item) => {
if (obj[item.type]) {
obj[item.type].push(item);
} else {
obj[item.type] = [item];
return obj;
}, {});
console.log(result);
输出结果为:
```javascript
fruit: [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'orange', type: 'fruit' },
{ name: 'pear', type: 'fruit' },
{ name: 'grape', type: 'fruit' }
vegetable: [
{ name: 'carrot', type: 'vegetable' },
{ name: 'broccoli', type: 'vegetable' },
{ name: 'tomato', type: 'vegetable' },
{ name: 'pepper', type: 'vegetable' },
{ name: 'potato', type: 'vegetable' }
在这个示例中,我们将 `arr` 数组中的元素按照 `type` 属性进行归类,得到一个包含 `fruit` 和 `vegetable` 两个属性的对象。每个属性对应一个数组,包含相同 `type` 属性值的元素。