使用.map和.filter格式化数据

时间:2019-07-05 06:28:27

标签: javascript arrays json object

当我获取数据库时,我从数据库中得到了以下类型的结果。我尝试了很多事情,并搜索了Google,但找不到任何东西。请帮我解决一下这个。谢谢。

{ metaData:
   [ { name: 'ID' },
     { name: 'NAME' },
     { name: 'LED_ID' },
     { name: 'LED_ORG_ID' },
     { name: 'COMPANY_ADD' },
     { name: 'STATE_CODE' },
     { name: 'CIN_NO' } ],
  rows:
   [ [ 1,
       'company name',
       2481,
       '161',
       'address ',
       '27',
       'number' ],
     [ 2,
       'company name2',
       2581,
       '164',
       'address 2',
       '27',
       'number2' ]
}
}

我正在尝试获取以下格式化的数据

{
 data:[
 {
  ID:1,
  NAME:'company name',
  LED_ID:2481,
  LED_ORG_ID: '161',
  COMPANY_ADD:'address',
  STATE_CODE:'27',
  CIN_NO:'number'
},
 {
  ID:2,
  NAME:'company name 2',
  LED_ID:2581,
  LED_ORG_ID: '164',
  COMPANY_ADD:'address 2',
  STATE_CODE:'27',
  CIN_NO:'number 2'
}
]
}

4 个答案:

答案 0 :(得分:2)

您可以使用array.map()Object.fromEntires()

let data = { metaData:
   [ { name: 'ID' },
     { name: 'NAME' },
     { name: 'LED_ID' },
     { name: 'LED_ORG_ID' },
     { name: 'COMPANY_ADD' },
     { name: 'STATE_CODE' },
     { name: 'CIN_NO' } ],
  rows:
   [ [ 1,
       'company name',
       2481,
       '161',
       'address ',
       '27',
       'number' ],
     [ 2,
       'company name2',
       2581,
       '164',
       'address 2',
       '27',
       'number2' ]
   ]
}

let result = data.rows.map(
        entry => Object.fromEntries(
            entry.map((x, i) => [data.metaData[i].name, x])
        )
    )

console.log(result)

编辑:外部map转换rows,因此将返回两个对象。内层将所有值转换为["ID", 1]之类的格式。该数组数组作为参数传递到Object.fromEntries中,{{1}}根据这些对创建一个新对象。

答案 1 :(得分:2)

mapflatMapreduce结合使用:

const metaData = [{name:'ID'},{name:'NAME'},{name:'LED_ID'},{name:'LED_ORG_ID'},{name:'COMPANY_ADD'},{name:'STATE_CODE'},{name:'CIN_NO'}];
const rows = [[1,'company name',2481,'161','address ','27','number'],[2,'company name2',2581,'164','address 2','27','number2']];

const res = rows.flatMap(e => e.map((f, i) => ({ [metaData[i].name]: f })).reduce((a, c) => ({ ...a, ...c }), {}));

console.log(res);

感谢马克·迈耶(Mark Meyer),提供了更出色的解​​决方案:

const res = rows.map(e => e.reduce((a, c, i) => ({ ...a, ...{ [metaData[i].name]: c }}), {});

答案 2 :(得分:2)

您可以先获取密钥,然后从条目中映射对象。

var data = { metaData: [{ name: 'ID' }, { name: 'NAME' }, { name: 'LED_ID' }, { name: 'LED_ORG_ID' }, { name: 'COMPANY_ADD' }, { name: 'STATE_CODE' }, { name: 'CIN_NO' }], rows: [[1, 'company name', 2481, '161', 'address ', '27', 'number'], [2, 'company name2', 2581, '164', 'address 2', '27', 'number2']] },
    keys = data.metaData.map(({ name }) => name),
    result = { data: data.rows.map(a => Object.fromEntries(keys.map((k, i) => [k, a[i]]))) };

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:1)

onStart

可能会更好...