簡體   English   中英

如何在 NodeJs 中刪除 TextRow 並將字符串添加到 JSON

[英]How to remove TextRow and add a string to JSON in NodeJs

我想刪除 TextRow 並向 NodeJs 中的 JSON 添加一個字符串( true )。 我在我的代碼下面添加了。

Node.js 代碼:

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

group數據:

[
  TextRow { name: '/products', email: '111@gmail.com' },
  TextRow { name: '/products', email: '222@gmail.com' },
  TextRow { name: '/sales', email: '111@gmail.com' },
  TextRow { name: '/sales', email: '222@gmail.com' },
  TextRow { name: '/sales', email: '333@gmail.com' },
  TextRow { name: '/sales', email: '444@gmail.com' },
  TextRow { name: '/finance', email: '333@gmail.com' },
  TextRow { name: '/finance', email: '444@gmail.com' },
]

我的 output:

{
  '/products': [
    TextRow { name: '/products', email: '111@gmail.com' },
    TextRow { name: '/products', email: '222@gmail.com' },
  ],
  '/sales': [
    TextRow { name: '/products', email: '111@gmail.com' },
    TextRow { name: '/products', email: '222@gmail.com' },
    TextRow { name: '/products', email: '333@gmail.com' },
    TextRow { name: '/products', email: '444@gmail.com' },
  ],
  '/products': [
    TextRow { name: '/products', email: '333@gmail.com' },
    TextRow { name: '/products', email: '444@gmail.com' },
  ],
}

Output 應該是:

{
  '/products': [
    {
      '111@gmail.com': true,
      '222@gmail.com': true,
    }
  ],
  '/sales': [
    {
      '111@gmail.com': true,
      '222@gmail.com': true,
      '333@gmail.com': true,
      '444@gmail.com': true,
    }
  ],
  '/finance': [
    {
      '333@gmail.com': true,
      '444@gmail.com': true,
    }
  ]
}

與其推送整行,不如創建一個新的 object。 我不太清楚為什么你的最終 output 是一個具有單個 object 的數組,或者為什么每個 email 都有一個true

const key = obj[property];
if (!acc[key]) {
  acc[key] = [{}];
}
acc[key][0][obj.email] = true;
return acc;

這樣做會產生一個 object,其鍵是name ,值是一個數組,每個數組都有一個 object,其鍵是 email 地址。

這是一個關於你應該如何做的例子。 它會給你預期的結果

 const list = [{ TextRow: { name: '/products', email: '111@gmail.com' } }, { TextRow: { name: '/products', email: '222@gmail.com' } }, { TextRow: { name: '/sales', email: '111@gmail.com' } }, { TextRow: { name: '/sales', email: '222@gmail.com' } }, { TextRow: { name: '/sales', email: '333@gmail.com' } }, { TextRow: { name: '/sales', email: '444@gmail.com' } }, { TextRow: { name: '/finance', email: '333@gmail.com' } }, { TextRow: { name: '/finance', email: '444@gmail.com' } }, ] const result = list.reduce((acc, x) => { const name = x['TextRow']['name']; const obj = { [x['TextRow'].email]: true }; if (acc[name]) { acc[name].push(obj) } else { acc[name] = [obj]; } return acc; }, []) console.log(result)

暫無
暫無

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

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