簡體   English   中英

javascript返回嵌套對象的數組並排列相似的類型

[英]javascript return array of nested object and arrange similar types

javascript返回嵌套對象的數組並排列相似的類型

我有東西

let obj1 = { categoryId:1, category:"Fruits", name:"Orange"}
let obj2 = { categoryId:1, category:"Fruits",name:"Apple"}
let obj3 = { categoryId:2, category:"Vegetables", name:"Onion"} 
let obj4 = { categoryId:2, category:"Vegetables", name:"Ginger"}....etc

我想從該數組創建嵌套對象數組:

let result =   

 [
         {
          name: "Fruits", values: [
            {
            "categoryId": 1,
            "category": "Fruits",
            "name": "Orange"
            }, 
            {
            "categoryId": 1,
            "category": "Fruits",
            "name": "Apple"
          }
         ]
        },
         { name:"Vegetables", values: [
            {
            "categoryId": 2,
            "category": "Vegetables",
            "name": "Onion"
            }, 
            {
            "categoryId": 2,
            "category": "Vegetables",
            "name": "Ginger"
          }
         ]
        }
    ]

我正在尋找一種並非一次全部添加到地圖的功能

addtoArray( obj1);
addtoArray( obj2); 
addtoArray( obj3); 
addtoArray( obj4);....etc 

還有一個刪除功能:

removeFromArray( obj1);

在刪除對象中不能相同:

{ categoryId:1, category:"Fruits", name:"Orange", newItem:"newvalue"}

應該使用category:"Fruits"參考刪除它

刪除對象,直到組中沒有更多對象。 然后,該組也將被刪除。

我嘗試的是下面

function addtoArray(collection, object) {
    if (!collection[object.category]) {
        collection[object.category] = [object];
        return;
    }
    if (collection[object.category].includes(object)) return;
    collection[object.category].push(object);
}

function removeFromArray(collection, object) {
    if (!collection[object.category]) return;
    var index = collection[object.category].indexOf(object);
    if (index === -1) return;
    collection[object.category].splice(index, 1);
    if (!collection[object.category].length) delete 
    collection[object.category];
}

var obj1 = { categoryId: 1, category: "Fruits", name:"Orange" },
    obj2 = { categoryId: 1, category: "Fruits", name:"Apple" },
    obj3 = { categoryId: 2, category: "Vegetables", name:"Onion" },
    obj4 = { categoryId: 2, category: "Vegetables", name:"Ginger" },
    collection = {};

請指導我!

用於添加到數組的函數:

var arr=[];

const addToArray=(arr,obj)=>{
  const index=findByName(arr,obj.category);
  if(index>-1){
    arr[i].values.push(obj)
  }else{
    arr.push({
      name:obj.category,
      values:[obj]
    })
  }
}
const findByName=(arr,name)=>{
  for(var i=0;i<arr.length;i++){
    if(arr[i].name===name)
      return i;
  }
  return -1;
}

addToArray(arr,obj1)

由於您要對數據進行各種查找,因此不建議使用數組。 每次要取出一個對象時,都需要遍歷它。 而是使用帶有一些幫助程序的類。

第一步是向您的數據添加唯一ID:

let obj1 = { id: 0, categoryId:1, category:"Fruits", name:"Orange"}
let obj2 = { id: 1, categoryId:1, category:"Fruits",name:"Apple"}
let obj3 = { id: 2, categoryId:2, category:"Vegetables", name:"Onion"} 
let obj4 = { id: 3, categoryId:2, category:"Vegetables", name:"Ginger"}

第二部分是創建一個類來保存此數據並允許您對其進行操作:

class MyCollection {
  constructor() {
    this.items = {};
  }

  addItem(item) {
    this.items[item.id] = item;
  }

  removeItem(item) {
    delete this.items[item.id]
  }

  removeGroup(group) {
    for(key in this.items) {
      if(this.collection[key] === group) {
        delete this.collection[key];
      }
    }
  }

  toArray() {
    return Object.values(this.items);
  }

}

用法:

const collection = new MyCollection();
collection.add(obj1);
collection.add(obj2);
collection.add(obj3);
collection.removeGroup("Fruits");
collection.items; // {2: { id: 2, categoryId:2, category:"Vegetables", name:"Onion"} }

//or should you desire to return an array
collection.toArray(); // [{ id: 2, categoryId:2, category:"Vegetables", name:"Onion"}]

結構是否像您上面顯示的那樣? 我認為,以下結構會更簡潔:

const result = {
  Fruits: [ {categoryId: 1, category: "Fruits", name: "orange"}, ... ],
  Vegetables: [ ... ]
}

通過這種結構,您的代碼將如下所示:

let obj1 = { categoryId:1, category:"Fruits", name:"Orange"}
let obj2 = { categoryId:1, category:"Fruits",name:"Apple"}
let obj3 = { categoryId:2, category:"Vegetables", name:"Onion"} 
let obj4 = { categoryId:2, category:"Vegetables", name:"Ginger"}

const objs = [ obj1, obj2, obj3, obj4 ]

const addToCollection = (collection, obj) => {
    if (!collection[obj.category]) {
        collection[obj.category] = []
    }
    collection[obj.category].push(obj)
}

const removeFromCollection = (collection, obj) => {
    if (!collection[obj.category]) return

    collection[obj.category] = collection[obj.category].filter((o) => {
        return o.name !== obj.name
    })
}


const result = {}

objs.forEach((obj) => {
    addToCollection(result, obj)
})

console.log(result)

removeFromCollection(result, obj2)

console.log(result)

這也非常有效,因為可以快速找到正確的類別。

輸出:

{
  Fruits: [
    { categoryId: 1, category: 'Fruits', name: 'Orange' },
    { categoryId: 1, category: 'Fruits', name: 'Apple' }
  ],
  Vegetables: [
    { categoryId: 2, category: 'Vegetables', name: 'Onion' },
    { categoryId: 2, category: 'Vegetables', name: 'Ginger' }
  ]
}


{
  Fruits: [
    { categoryId: 1, category: 'Fruits', name: 'Orange' }
  ],
  Vegetables: [
    { categoryId: 2, category: 'Vegetables', name: 'Onion' },
    { categoryId: 2, category: 'Vegetables', name: 'Ginger' }
  ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM