添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
勤奋的雪糕  ·  RAM vs ROM vs Cache ...·  2 月前    · 
豪情万千的打火机  ·  NOVO Archives - ...·  11 月前    · 
风流的芹菜  ·  源码编译安装httpd - ...·  1 年前    · 
{ 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` 属性的元素。