javascript - 如何通过组变量更改 JSON 结构?

标签 javascript arrays json algorithm

<分区>

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

我的旧 JSON:

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

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

[
  {
    "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 })) }
        ));
    })
}

我的结果:

enter image description here

最佳答案

在您的解决方案中,您正在调用 .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);

关于javascript - 如何通过组变量更改 JSON 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53871175/

相关文章:

javascript - 为什么这个外部民意调查的问题是环绕的?

c - 如何打印函数返回的数组

php - 如何将 javascript 中的数组传递给 php - LARAVEL?

c - 如何在 C 循环中不断定义然后清空字符串?

java - 如何使用正则表达式来识别JSON字符串中的错误消息?

javascript - 安全的 Node.js 聊天(避免 XSS)

javascript - 使用 JQuery 样式化嵌套滚动条

c++ - 有没有一种方法可以检查 QJsonObject 对象是否包含特定属性?

javascript - 链接函数和 Controller 函数如何共享 Angular Directive(指令)中的知识?

json - 如何在子 OPENJSON 的结果上使用 OPENJSON