簡體   English   中英

將數組轉換為 object 個鍵值對

[英]convert an array to an object of key value pairs

如果我有一個字符串數組,例如:

['person,item,cost,amount',
  'John,shoes,200,2']

我怎么能把它轉換成類似於以下內容的 object:

{  
   'John':[  
      {  
         item:'shoes',
         cost:'200',
         amount:'2',
         totalPriceForItems:'400'
      }

如果我理解正確,你可以嘗試這樣的事情:

 const convert = data => { const [columnsText, ...items] = data; const columns = columnsText.split(','); return items.reduce((acc, text) => { const { person, ...entries } = Object.fromEntries(text.split(',').map((value, i) => [columns[i], value])); entries.totalPriceForItems = String(entries.cost * entries.amount); if(acc[person]) { acc[person].push(entries); } else { acc[person] = [entries]; } return acc; }, {}); }; const result = convert([ 'person,item,cost,amount', 'John,shoes,200,2', 'Bob,glasses,50,3', 'John,shirts,100,5', ]); console.log(result);

根據您的評論,

我有 8 行“John,shoes,200,2”,但在同一個數組中有不同的數量。 'person,item,cost,amount'只在數組的開頭提到一次

據我了解,您有一個帶有標題和多行的 csv。 如果是這種情況,那么您的數據將類似於以下內容:

data = [
  'person,item,cost,amount',
  'John,shoes,200,2',
  'Adam,pants,60,1',
  'Kelly,skirt,180,2',
  'John,skirt,150,3'
]

那么你可以考慮下面的方法,它足夠通用以適應不同的標題,以及具有重復鍵(人名)的多個數據行。

// here, you define a function to transform each row of your data,
// like parsing numeric attributes and calculating the totals
function transform(row) {
  row.cost = Number.parseInt(row.cost)
  row.amount = Number.parseInt(row.amount)
  row.total = row.cost * row.amount
  return row
}

// The following logic is generic, and can be used 
// to map and aggregate any kind of csv with headers
hdrs = data.shift().split(',').slice(1)
rows = data.map(r => r.split(',')).reduce((acc, [n, ...kvs]) => 
  ({ ...acc, [n]: [...acc[n] || [], transform(Object.fromEntries(kvs.map((v, i) => [hdrs[i], v])))] }), {})

Output:

{ 
  John: [
    { item: "shoes", cost: 200, amount: 2, total: 400 }, 
    { item: "skirt", cost: 150, amount: 3, total: 450 }], 
  Adam: [
    { item: "pants", cost:  60, amount: 1, total:  60 }], 
  Kelly: [
    { item: "skirt", cost: 180, amount: 2, total: 360 }]
}

暫無
暫無

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

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