【问题标题】:How can i change JSON structure by group variable? [duplicate]如何通过组变量更改 JSON 结构? [复制]
【发布时间】:2018-12-20 15:03:31
【问题描述】:

我正在尝试更改 JSON 结构以推送到我的数据库

我的旧 JSON:

       [
          {"name": "nameGallery"},
          {"img": "1.jpg"},
          {"img": "2.img"}
       ]

我想像这样将“img”变量分组到“Images”数组中:

[
  {
    "name": "nameGallery",
    "Images": [
              {"img": "1.jpg"},
              {"img": "2.img"}
              ]
  }
]

我正在尝试使用 object.assign 来管理它,但我不知道为什么会出错。

function getData() {
    fetch('text/upload.json').then((res) => res.json())
    .then((data) => {
        console.log(data);
        data = data.map(o => Object.assign({}, o,
        { Images: o.Images.map(({ img }) => ({ img: img })) }
        ));
    })
}

我的结果:

【问题讨论】:

  • 你确定数据有价值吗? console.log(data) 显示了什么?
  • @basic 可能是o.Images 那是undefined
  • 那是因为o对象中没有叫Images的属性。
  • 另一个问题是你需要展示一个更真实的数据样本来帮助别人为你提供更好的答案。您能否在数组中显示原始 JSON 的更多信息,而不是您在此处拥有的信息?
  • @asiby 谢谢你,下次我会更关心真实的数据样本。

标签: javascript arrays json algorithm


【解决方案1】:

在您的解决方案中,您调用 .map,这将为您的初始数据中的每个数组条目创建一个数组条目。

正如您所描述的,您期望一个对象作为结果,而不是一个对象数组。那么请看以下内容:

const data = [{
    name: 'nameGallery',
  },
  {
    img: '1.jpg',
  },
  {
    img: '2.img',
  },
];

// You want to create a new object using all the others objects
const ret = data.reduce((tmp, x) => {
  // If the key below is 'img', we push the object into 'Images'
  // void 0 means undefined
  if (x.img !== void 0) {
    tmp.Images.push(x);

    return tmp;
  }

  // If the key is not 'img'
  // We copy the keys into tmp
  return {
    ...tmp,

    ...x,
  };
}, {
  // initialize 'Images' key here it won't be undefined
  // when pushing the first data
  Images: [],
});

console.log(ret);

【讨论】:

  • 非常感谢,我知道了:)
【解决方案2】:

你可以试试这样的:

function getData() {
    fetch('text/upload.json').then((res) => res.json())
    .then((data) => {
        const name = data.find(o => !!o.name);

        return {
          name: name.name,
          Images: data.filter(o => !!o.img)
        };
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 2013-05-06
    • 2022-08-23
    • 2020-09-15
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多