首页 \ 问答 \ 组合json对象并保留重复键(Combine json objects and keep duplicate keys)

组合json对象并保留重复键(Combine json objects and keep duplicate keys)

我想组合两个包含json对象的数组,但是通过在键前添加一些文本来保留重复键。 在下面的示例中,来自对象json2的数据覆盖了对象json1,因为它们具有相同的键,但我也希望保留第一个对象的数据。 谢谢。

var json1 = [
  {
    "Column1": "json1",
    "Column2": "json1",
  },
  {
    "Column1": "json1",
    "Column2": "json1",
  }
];
var json2 = [
  {
    "Column1": "json2",
    "Column2": "json2",
  },
  {
    "Column1": "json2",
    "Column2": "json2",
  }
];

console.log(angular.extend(json1, json2));

正在回归

[
  {
    "Column1": "json2",
    "Column2": "json2",
  },
  {
    "Column1": "json2",
    "Column2": "json2",
  }
];

但我想要

[
  {
    "json1Column1": "json1",
    "json1Column2": "json1",
    "json2Column1": "json2",
    "json2Column2": "json2",
  },
  {
    "json1Column1": "json1",
    "json1Column2": "json1",
    "json2Column1": "json2",
    "json2Column2": "json2",
  }
];

I want to combine two arrays containing json objects but keep the duplicate keys by prepending the keys with some text. In the example below the data from the object json2 is overwriting the object json1 because they have the same keys but I want to keep the data from the 1st object as well. Thanks.

var json1 = [
  {
    "Column1": "json1",
    "Column2": "json1",
  },
  {
    "Column1": "json1",
    "Column2": "json1",
  }
];
var json2 = [
  {
    "Column1": "json2",
    "Column2": "json2",
  },
  {
    "Column1": "json2",
    "Column2": "json2",
  }
];

console.log(angular.extend(json1, json2));

is returning

[
  {
    "Column1": "json2",
    "Column2": "json2",
  },
  {
    "Column1": "json2",
    "Column2": "json2",
  }
];

but I want

[
  {
    "json1Column1": "json1",
    "json1Column2": "json1",
    "json2Column1": "json2",
    "json2Column2": "json2",
  },
  {
    "json1Column1": "json1",
    "json1Column2": "json1",
    "json2Column1": "json2",
    "json2Column2": "json2",
  }
];

原文:https://stackoverflow.com/questions/35296614
更新时间:2023-04-24 20:04

最满意答案

德米特里·索斯尼科夫已经回答了你的问题。 每个<script>元素作为ECMAScript规范定义的程序执行。 单个页面中的每个程序都使用一个全局对象。 那真的是这样。


Dmitry Soshnikov has answered your question. Every <script> element is executed as a Program, as defined by the ECMAScript specification. There is one global object that each Program within a single page uses. And that's really it.

相关问答

更多
  • 在css方式...我尝试在已经加载的页面上插入一些css并且滚动条从未改变过? chrome.tabs.insertCSS(tab.id,{code:"::-webkit-scrollbar {width: 0 !important; height: 0 !important}"}); ...甚至尝试将它连接到头部,但也没有工作.... insertNoScrollBars=function (){ if(document.getElementById('HideScrollBars') == null ...
  • 答案取决于脚本标记的位置以及您添加的方式: 与标记内联的脚本标记与浏览器对该标记的处理(除了#2)进行同步执行,因此,如果 - 例如 - 这些标记引用外部文件,它们往往会减慢页面的处理速度。 (这就是浏览器可以处理document.write语句,改变它们正在处理的标记。) 在某些浏览器上,具有defer属性的脚本标记在DOM完全呈现之后才能被执行。 当然这些不能使用document.write 。 (类似地,有一个async属性使脚本异步,但我不太了解或支持多少; 详细信息 。) DOM加载后(通过inn ...
  • 德米特里·索斯尼科夫已经回答了你的问题。 每个