通过JSON密钥的Node Js Transformation JSON

时间:2019-03-20 02:39:40

标签: javascript arrays node.js reactjs typescript

我想过滤以下JSON结果。但我无法转换。

const result = 
[
  {
    id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
    type: 'Interstitial (320x480)',
    country: 'ABC',
    enabled: true,
    rank: 1,
    link: '',
    }];

[{
  "Interstitial (320x480)" : {
  "enabled": true,
  "rank": 1,
}];

这是我的代码

const result = 
[
 {
  id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
  type: 'Interstitial (320x480)',
  country: 'ABC',
  enabled: true,
  rank: 1,
  link: '',
 }];

const fields = ['type', 'rank', 'enabled'];
const tranform = Object.assign({}, ...fields
  .filter(key => !!result[key]).map(key => ({ [key]: result[key] })));
console.log(tranform);

上面的代码,我想提取字段数组中提到的键

并且期望的结果应该是

[{
  "Interstitial (320x480)" : {
  "enabled": true,
  "rank": 1,
}];

先谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用函数map和计算属性名称来使用变量动态创建密钥。

这是假设fields中的第一个索引是主键,下一个索引是要提取的值。

const result = [{
  id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
  type: 'Interstitial (320x480)',
  country: 'ABC',
  enabled: true,
  rank: 1,
  link: '',
}],
      fields = ['type', 'rank', 'enabled'],
      [key, ...others] = fields;
      
const mapped = result.map(o => ({[o[key]]: others.reduce((a, c) => Object.assign({}, a, {[c]: o[c]}), {})}));

console.log(mapped);

答案 1 :(得分:0)

检查以下代码段

 const results = [{
      id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
      type: 'Interstitial (320x480)',
      country: 'ABC',
      enabled: true,
      rank: 1,
      link: '',
    }];

    const transformed = results.map(result =>
      ({ [result.type]: { enabled: result.enabled, rank: result.rank } }));

    console.log(transformed);

答案 2 :(得分:0)

结果是一个对象数组,因此只需在代码中更改此行即可

14c14
<   .filter(key => !!result[key]).map(key => ({ [key]: result[key] })));
---
>   .filter(key => !!result[0][key]).map(key => ({ [key]: result[0][key] })));

但是,如果结果在数组中包含多个对象,则使transform函数并将其映射到结果上。

const result = [{
  id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
  type: 'Interstitial (320x480)',
  country: 'ABC',
  enabled: true,
  rank: 1,
  link: '',
}];

const fields = ['rank', 'enabled'];
const tranform = r => ({
  [r.type]: Object.assign({}, ...fields
    .filter(key => !!r[key]).map(key => ({
      [key]: r[key]
    })))
});
console.log(result.map(tranform));