【问题标题】:How to flatten properties inside json array in javascript? [closed]如何在javascript中展平json数组中的属性? [关闭]
【发布时间】:2018-08-30 15:26:25
【问题描述】:

我尝试了一些代码来展平,但它展平了整个 json。我的要求是仅展平位置属性。

我有以下 json 数组:

[{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position:{lat: 59.441388, lng: 10.579491}
time:"15-05-2016"
type:"Teine"
userId:""
},
{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position:{lat: 59.441388, lng: 10.579491}
time:"15-05-2016"
type:"Teine"
userId:""
}]

我想要这样的输出:

[{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position.lat:59.441388, 
position.lng: 10.579491,
time:"15-05-2016"
type:"Teine"
userId:""
},
{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position.lat: 59.441388, 
position.lng: 10.579491,
time:"15-05-2016"
type:"Teine"
userId:""
}]

有人可以建议我如何在 javascript 中实现上述输出吗?

【问题讨论】:

  • 嗯...第二个 JSON 不是有效的 JSON。 :(
  • position.lat : 59.441388 无效。可能是"position.lat" : 59.441388,这是你想要的吗?
  • 你为什么要这样做?对象的原始版本(JavaScript 对象,而不是“JSON 对象”)允许您将position 子属性引用为array[n].position.latarray[n].position.lng。您想要的结果使这变得不那么方便了。
  • 我正在使用 file-saver.js 将 json 数组导出到 excel。它适用于平面 json。但是如果我使用上面的 json,那么它将位置列导出为空白。所以我需要 position.lat , position.lng

标签: javascript typescript


【解决方案1】:

对于灵活的解决方案,您可以使用recursion。请注意,该函数调用自身来遍历对象:

$ cat test.js && echo "\n-------\n" && node test.js
const subject = {a:1, b:2, c:{d:3, e:{f:4, g:5}}};

function flatten (obj){
  const result = {};
  Object.keys(obj).forEach(key => {
    const value = obj[key];
    if (typeof value === 'object') {
      const flattened = flatten(value);
      Object.keys(flattened).forEach( subKey => {
         result[`${key}.${subKey}`] = flattened[subKey]
      })
    } else {
      result[key] = value
    }
  });
  return result;
}

console.log(JSON.stringify(flatten(subject), null, 2));

-------

{
  "a": 1,
  "b": 2,
  "c.d": 3,
  "c.e.f": 4,
  "c.e.g": 5
}

【讨论】:

    【解决方案2】:

    或使用 Array.map()

    const arr = [
    {
      amount:"1 teine med 110 mtr iletau",
      comment:"",
      created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)",
      locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).",
      position:{lat: 59.441388, lng: 10.579491},
      time:"15-05-2016",
      type:"Teine",
      userId:""
    },
    {
      amount:"1 teine med 110 mtr iletau",
      comment:"",
      created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)",
      locationDescription:"På vestsiden av Jeløya, utenfor Moss.(Oslofjorden).",
      position:{lat: 59.441388, lng: 10.579491},
      time:"15-05-2016",
      type:"Teine",
      userId:""
    }
    ];
    
    
    const flattenPositions = o => {
      o["position.lng"] = o.position.lng;
      o["position.lat"] =  o.position.lat;
      delete o.position;
      return o;
     };
    
    arr = arr.map(el=>flattenPositions(el));
    
    
    console.log(arr);

    【讨论】:

    • 你仍然改变原始对象。
    • 你说得对! (但是这就是操作人员想要的。但不需要新的声明,你是对的)
    • 顺便说一句,我经常阅读您的答案(并从中学到很多东西),那么为什么今天的迭代与地图相比?
    • 这是我的问题吗?如果是这样,我写道,由于切换数组,该映射不起作用。外部数组反映结果的内部数组,反之亦然。给定 15 x 4 想要 4 x 15。
    • 是的。感谢您的宝贵时间。
    【解决方案3】:

    您可以迭代数组并构建新属性并删除 position.

    var array = [{ amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }, { amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }];
    
    array.forEach(o => {
        Object.assign(o, { 'position.lat': o.position.lat, 'position.lng': o.position.lng });
        delete o.position;
    });
    
    console.log(array);

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 1970-01-01
      • 2021-12-27
      • 2019-11-16
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      相关资源
      最近更新 更多