【问题标题】:Node Js Transformation JSON by JSON key通过 JSON 键的 Node Js 转换 JSON
【发布时间】:2019-08-10 16:11:54
【问题描述】:

我想过滤以下 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,
}];

提前致谢。

【问题讨论】:

  • const fields = ['type', 'rank', 'enabled']; -> 第一个索引是对对象内的下一个索引进行分组的关键吗?

标签: javascript arrays node.js reactjs typescript


【解决方案1】:

您可以使用函数map 和computed-property-name 使用变量动态创建密钥。

假设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);

【讨论】:

  • 结果不是硬编码的,我只是在我的代码中解释过
【解决方案2】:

检查以下代码sn -p

 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);

【讨论】:

    【解决方案3】:

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

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

    但是,如果结果在数组中包含多个对象,请转换一个函数并将其映射到结果上。

    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));

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 2016-07-27
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多