jquery 一种在json中合并/合并对象的方法

mrzz3bfm  于 2023-03-07  发布在  jQuery
关注(0)|答案(1)|浏览(109)

我有一个不方便的数据输出,如下所示:

[
    {
        "object_a": {
            "1": "some value of 1",
            "2": "some value of 2",
            "3": ""
        },
        "obejct_b": {
            "1": "",
            "2": "",
            "3": "some value of 3"
        },
        ..some other objects..
    }
    {
        "object_a": {
            "1": "some value of 1",
            "2": "",
            "3": "some value of 3"
    },
        "obejct_b": {
            "1": "",
            "2": "some value of 2",
            "3": ""
        },
        ..some other objects..
    }
    {
        "object_a": {
            "1": "",
            "2": "some value of 2",
            "3": ""
        },
        "obejct_b": {
            "3": "some value of 3",
            "1": "some value of 1",
            "2": ""
        },
        ..some other objects..
    }
]

我不知道还要添加什么。它看起来很简单。不幸的是,我不能更改输出格式。问题是有些数据在“object_a”中,有些在“object_b”中。
所需输出如下所示:

[
    {
        "object": {
            "1": "some value of 1",
            "2": "some value of 2",
            "3": "some value of 3"
        }
        ..some other objects..
    }
    {
        "object": {
            "1": "some value of 1",
            "2": "some value of 2",
            "3": "some value of 3"
        },
        ..some other objects..
    }
        {
        "object": {
            "2": "some value of 2",
            "3": "some value of 3",
            "1": "some value of 1",
        },
        ..some other objects..
    }
]

我找不到用jQuery合并/合并两个对象的方法。
谢谢。

qnakjoqk

qnakjoqk1#

必须做出一些假设:

  • 顶层数组中的每个对象都将具有相同的两个(且只有这两个)属性object_aobejct_b [sic]。
  • 每个object_aobejct_b将具有相同的属性集。
  • 对于object_a中的任何空字符串键,“merged”结果中的值应该是对应的obejct_b的值。

基于这些假设,我将使用以下代码(注意,我保留了obejct_b中的拼写错误)。

const output = [
  {
    "object_a": {
      "1": "some value of 1",
      "2": "some value of 2",
      "3": ""
    },
    "obejct_b": {
      "1": "",
      "2": "",
      "3": "some value of 3"
    },
    "some other object": {
      "foo" : "bar"
    }
  },
  {
    "object_a": {
      "1": "some value of 1",
      "2": "",
      "3": "some value of 3"
    },
    "obejct_b": {
      "1": "",
      "2": "some value of 2",
      "3": ""
    }
  },
  {
    "object_a": {
      "1": "",
      "2": "some value of 2",
      "3": ""
    },
    "obejct_b": {
      "3": "some value of 3",
      "1": "some value of 1",
      "2": ""
    }
  }
];

const merged = output.map(item => {
  // assumes object_a and obejct_b have the same keys
   const mergedAB =  Object.keys(item.object_a).reduce((acc, key) => {
    // assuming typo in "obejct_b" is intentional
    acc[key] = item.object_a[key] || item.obejct_b[key];
    return acc;
  }, {});
  
  const others = { ...item };
  delete others.object_a;
  delete others.obejct_b;
  
  return {
    object: mergedAB,
    ...others
  }
});

document.body.innerHTML = `<pre>${JSON.stringify(merged, null, 2)}</pre>`;

相关问题