【问题标题】:How to change json in array in forEach loop ? JS [duplicate]如何在 forEach 循环中更改数组中的 json? JS [重复]
【发布时间】:2021-03-05 14:36:48
【问题描述】:

我需要更改 JSON。

我的 JSON 数组示例:

{
    // ...any properties
    point: [
      location: {
        latitude: 0,
        longitude: 0 
      },
      name: "Point1",
      pointId: 1
    ]
}

然后我循环遍历数组:

data.points.forEach((formData: IAddress) => {
  control.push(this.initiateForm(formData));
});

得到的结果是:

{
    location: {
      latitude: 0,
      longitude: 0 
    },
    name: "Point1",
    pointId: 1
}

想要的结果是:

{
  latitude: 0,
  longitude: 0  
  name: "Point1",
  pointId: 1
}

只需删除位置 JSON,就好像从该位置弹出经度和纬度一样。

【问题讨论】:

  • 那不是JSON,那些是对象
  • Ok Objects .. 结果很重要 :)
  • this.initiateForm 函数是做什么的
  • 语法错误。你不能拥有不存在的[ prop : { } ]
  • "结果很重要 :)" - 重要的是了解你使用的东西。

标签: javascript


【解决方案1】:

您可以使用Array.mapobject destructuringspread

const original = {
    // ...any properties
    // Here, I assume the `points` is an array of objects instead of a buggy array/object
    points: [
      {
        location: {
          latitude: 0,
          longitude: 0 
        },
        name: "Point1",
        pointId: 1
      }
    ]
};

const result = original.points
  .map( ({location, ...rest}) => ({
    ...rest,
    ...location,
  }))

【讨论】:

    【解决方案2】:

    您可以使用Object.entriesObject.fromEntries 和展开 (...) 运算符做一些工作:

    const points =  [{
          location: {
            latitude: 0,
            longitude: 0 
          },
          name: "Point1",
          pointId: 1
        }];
    
    
    const result = points.map(p => {
      return {
        ...Object.fromEntries(Object.entries(p).filter(e =>  e[0] != "location")),
        ...p.location
      };
    });
    console.log(result)

    【讨论】:

    【解决方案3】:

    扁平化对象

    你想要像 flatten 但在对象上的东西,所以我很快就做了一些代码。

    不指定键(使用 typeof),但只指定一级对象。

    const arr = [
      {
        "location": {
          "latitude": 0,
          "longitude": 0
        },
        "name": "Point1",
        "pointId": 1,
        "extraObject": {
          "one": "value1",
          "two": "value2"
        }
      },
      {
        "location": {
          "latitude": 0,
          "longitude": 0
        },
        "name": "Point1",
        "pointId": 1
      }
    ]
    
    
    const newArr = arr.map(item => {
      return Object.keys(item).reduce((acc, key) => {
        if (typeof item[key] === 'object') {
          acc = {...acc, ...item[key]};
        } else {
          acc[key] = item[key];
        }
        return acc;
      }, {})
    })
    
    console.log(newArr);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-12
      • 2013-08-19
      • 2015-08-02
      • 2015-11-22
      • 2021-12-20
      • 2020-10-31
      • 2023-03-28
      • 2017-02-23
      相关资源
      最近更新 更多