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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14974864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:32:46  来源:igfitidea点击:

Combine or merge JSON on node.js without jQuery

javascriptjqueryjsonnode.js

提问by HP.

I have multiple JSONlike those

我有多个JSON这样的

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

They are not nesting or anything like that. Just basically different fields. I need to combine them into one single JSONin node.jslike this:

它们不是嵌套或类似的东西。只是基本上不同的领域。我需要像这样JSONnode.js中将它们组合成一个:

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

I can use jQueryjust fine. Here is a working example in the browser:

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

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

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

But if I do this in node.js, I don't want to load jQuery (which is a bit over use, plus node.js' jQuerydoesn't work on my Windowsmachine).

但是如果我在node.js 中这样做,我不想加载 jQuery(这有点过度使用,加上node.js 的 jQuery在我的Windows机器上不起作用)。

So is there a simple way to do things similar to $.extend()without jQuery?

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

采纳答案by James Allardice

A normal loop?

正常循环?

function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

var object3 = extend({}, object1, object2);

That's a basic starting point. You may want to add things like a hasOwnPropertycheck, or add some logic to handle the case where multiple source objects have a property with the same identifier.

这是一个基本的出发点。您可能想要添加诸如hasOwnProperty检查之类的内容,或者添加一些逻辑来处理多个源对象具有具有相同标识符的属性的情况。

Here's a working example.

这是一个工作示例

Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.

旁注:您所指的“JSON”实际上是普通的 JavaScript 对象。JSON 只是一种文本格式,与 JavaScript 共享一些语法。

回答by Ricardo Nolde

You should use "Object.assign()"

你应该使用“ Object.assign()

There's no need to reinvent the wheel for such a simple use case of shallow merging.

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

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.

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

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

Even the folks from Node.js say so:

甚至来自Node.js的人也这么说

_extendwas 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.

_extend从未打算在内部 NodeJS 模块之外使用。社区无论如何都找到并使用了它。它已被弃用,不应在新代码中使用。JavaScript 通过Object.assign.



Update:

更新:

You could use the spread operator

您可以使用扩展运算符

Since version 8.6, it's possible to natively use the spread operatorin Node.js. Example below:

8.6 版本开始,可以在 Node.js 中原生使用扩展运算符。下面的例子:

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

Object.assignstill works, though.

Object.assign不过仍然有效。



PS1: If you are actually interested in deep merging(in which internal object data -- in any depth -- is recursively merged), you can use packages like deepmerge, assign-deepor lodash.merge, which are pretty small and simple to use.

PS1:如果你真的对深度合并(其中内部对象数据——在任何深度——递归合并)感兴趣,你可以使用像deepmergeassign-deeplodash.merge这样的,它们非常小且易于使用用。

PS2: Keep in mind that Object.assign doesn't work with 0.X versions of Node.js. If you are working with one of those versions (you really shouldn't by now), you could use require("util")._extendas shown in the Node.js link above -- for more details, check tobymackenzie's answer to this same question.

PS2:请记住Object.assign 不适用于 Node.js 的 0.X 版本。如果您正在使用这些版本之一(您现在确实不应该使用),您可以使用require("util")._extend上面的 Node.js 链接中所示的内容——有关更多详细信息,请查看tobymackenzie 对同一问题的回答

回答by tobymackenzie

If using Node version >= 4, use Object.assign()(see Ricardo Nolde's answer).

如果使用 Node 版本 >= 4,请使用Object.assign()(参见Ricardo Nolde 的回答)。

If using Node 0.x, there is the built in util._extend:

如果使用 Node 0.x,则有内置的 util._extend:

var extend = require('util')._extend
var o = extend({}, {name: "John"});
extend(o,  {location: "San Jose"});

It doesn't do a deep copy and only allows two arguments at a time, but is built in. I saw this mentioned on a question about cloning objects in node: https://stackoverflow.com/a/15040626.

它不进行深度复制,一次只允许两个参数,但它是内置的。我在关于在节点中克隆对象的问题中看到了这一点:https: //stackoverflow.com/a/15040626

If you're concerned about using a "private" method, you could always proxy it:

如果您担心使用“私有”方法,您可以随时代理它:

// myutil.js
exports.extend = require('util')._extend;

and replace it with your own implementation if it ever disappears. This is (approximately) their implementation:

如果它消失了,用你自己的实现替换它。这是(大约)他们的实现:

exports.extend = function(origin, add) {
    if (!add || (typeof add !== 'object' && add !== null)){
        return origin;
    }

    var keys = Object.keys(add);
    var i = keys.length;
    while(i--){
        origin[keys[i]] = add[keys[i]];
    }
    return origin;
};

回答by AndyD

Underscore's extendis the easiest and quickest way to achieve this, like James commented.

下划线extend是实现这一目标的最简单快捷的方法,就像詹姆斯评论的那样。

Here's an example using underscore:

下面是一个使用下划线的例子:

var _ = require('underscore'), // npm install underscore to install
  object1 = {name: "John"},
  object2 = {location: "San Jose"};

var target = _.extend(object1, object2);

object 1 will get the properties of object2 and be returned and assigned to target. You could do it like this as well, depending on whether you mind object1 being modified:

对象 1 将获取对象 2 的属性并返回并分配给目标。你也可以这样做,这取决于你是否介意 object1 被修改:

var target = {};
_.extend(target, object1, object2);

回答by zim

Use merge.

使用合并

$ npm install merge

Sample code:

示例代码:

var merge = require('merge'), // npm install -g merge
    original, cloned;

console.log(

    merge({ one: 'hello' }, { two: 'world' })

); // {"one": "hello", "two": "world"}

original = { x: { y: 1 } };

cloned = merge(true, original);

cloned.x.y++;

console.log(original.x.y, cloned.x.y); // 1, 2

回答by Petr KOKOREV

I see that this thread is too old, but I put my answer here just in logging purposes.

我看到这个线程太旧了,但我把我的答案放在这里只是为了记录目的。

In one of the comments above you mentioned that you wanted to use 'express' in your project which has 'connect' library in the dependency list. Actually 'connect.utils' library contains a 'merge' method that does the trick. So you can use the 3rd party implementation without adding any new 3rd party libraries.

在上面的评论之一中,您提到您想在依赖项列表中有“connect”库的项目中使用“express”。实际上'connect.utils' 库包含一个'merge' 方法来解决这个问题。因此,您可以使用 3rd 方实现而无需添加任何新的 3rd 方库。

回答by Manu K Mohan

Here is simple solution, to merge JSON. I did the following.

这是合并JSON的简单解决方案。我做了以下事情。

  • Convert each of the JSON to strings using JSON.stringify(object).
  • Concatenate all the JSON strings using +operator.
  • Replace the pattern /}{/gwith ","
  • Parse the result string back to JSON object

    var object1 = {name: "John"};
    var object2 = {location: "San Jose"};
    var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))
    
  • 使用 将每个 JSON 转换为字符串JSON.stringify(object)
  • 使用+运算符连接所有 JSON 字符串。
  • 替换模式/}{/g","
  • 将结果字符串解析回 JSON 对象

    var object1 = {name: "John"};
    var object2 = {location: "San Jose"};
    var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))
    

The resulting merged JSON will be

结果合并的 JSON 将是

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

回答by Patrick Murphy

You can also use this lightweight npm package called absorb

你也可以使用这个名为吸收的轻量级 npm 包

It is 27 lines of code, 1kb and uses recursion to perform deep object merges.

它有 27 行代码,1kb,并使用递归来执行深度对象合并。

var absorb = require('absorb');
var obj1, obj2;

obj1 = { foo: 123, bar: 456 };
obj2 = { bar: 123, key: 'value' }

absorb(obj1, obj2);

console.log(obj1); // Output: { foo: 123, bar: 123, key: 'value' }

You can also use it to make a clone or only transfer values if they don't exist in the source object, how to do this is detailed in the link provided.

您还可以使用它来创建克隆或仅传输源对象中不存在的值,提供的链接中详细说明了如何执行此操作。

回答by Sushil Kumar

It can easy be done using Object.assign() method -

使用 Object.assign() 方法可以轻松完成 -

 var object1 = {name: "John"};
 var object2 = {location: "San Jose"};
 var object3 = Object.assign(object1,object2);
 console.log(object3);

now object3 is { name: 'John', location: 'San Jose' }

现在 object3 是 { name: 'John', location: 'San Jose' }

回答by Stenal P Jolly

There is an easy way of doing it in Node.js

在 Node.js 中有一种简单的方法可以做到

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

To combine/extend this we can use ...operator in ECMA6

为了组合/扩展它,我们可以...在 ECMA6 中使用运算符

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

var result = {
  ...object1,
  ...object2
}

console.log(result)