gpt4 book ai didi

javascript - 在没有 jQuery 的情况下在 node.js 上合并或合并 JSON

转载 作者:IT老高 更新时间:2023-10-28 12:43:28 25 4
gpt4 key购买 nike

我有多个类似的 JSON

var object1 = {name: "John"};
var object2 = {location: "San Jose"};

它们不是嵌套或类似的东西。只是基本上不同的领域。我需要在 node.js 中将它们组合成一个 JSON,如下所示:

{name: "John", location: "San Jose"}

我可以使用 jQuery 就好了。这是浏览器中的一个工作示例:

http://jsfiddle.net/qhoc/agp54/

但如果我在 node.js 中执行此操作,我不想加载 jQuery(这有点过度使用,加上 node.js' jQuery 不会不能在我的 Windows 机器上工作)。

那么有没有一种简单的方法来做类似于 $.extend() 而没有 jQuery 的事情?

最佳答案

你应该使用“Object.assign()

对于这样一个简单的浅层合并用例,无需重新发明轮子。

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed
console.log(obj === o1) // true

即使是来自 Node.js say so 的人:

_extend was never intended to be used outside of internal NodeJS modules. The community found and used it anyway.It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign.


更新:

您可以使用 spread operator

自从 version 8.6 , 可以原生使用 spread operator在 Node.js 中。示例如下:

let o1 = { a: 1 };
let o2 = { b: 2 };
let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }

Object.assign 仍然有效。


<支持>**PS1**:如果你真的对 **deep merging** 感兴趣(其中内部对象数据——在任何深度——被递归地合并),你可以使用像 [deepmerge][4]、[assign -deep][5] 或 [lodash.merge][6],它们非常小且易于使用。<支持>**PS2**:请记住,**Object.assign 不适用于 0.X 版本的 Node.js**。如果您正在使用其中一个版本(_您现在真的不应该_),您可以使用 `require("util")._extend`,如上面的 Node.js 链接所示——有关更多详细信息,请查看 [tobymackenzie's回答同样的问题](https://stackoverflow.com/a/22286375/36272)。

关于javascript - 在没有 jQuery 的情况下在 node.js 上合并或合并 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14974864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com