在没有jQuery的情况下在node.js上组合或合并JSON [英] Combine or merge JSON on node.js without jQuery
问题描述
我有多个 JSON
就像那些
var object1 = {名称:约翰};
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 ?正常循环?
function extend(target){
var sources = [] .slice.call(arguments,1);
sources.forEach(function(source){
for(var prop in source){
target [prop] = source [prop];
}
}) ;
返回目标;
}
var object3 = extend({},object1,object2);
这是一个基本的起点。您可能希望添加诸如 hasOwnProperty
之类的内容,或添加一些逻辑来处理多个源对象具有相同标识符的属性的情况。
这是工作示例。
旁注:你所说的JSON实际上是普通的JavaScript对象。 JSON只是一种与JavaScript共享语法的文本格式。
I have multiple JSON
like those
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 JSON
in node.js like this:
{name: "John", location: "San Jose"}
I can use jQuery just fine. Here is a working example in the browser:
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' jQuery doesn't work on my Windows machine).
So is there a simple way to do things similar to $.extend()
without jQuery?
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 hasOwnProperty
check, or add some logic to handle the case where multiple source objects have a property with the same identifier.
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.
这篇关于在没有jQuery的情况下在node.js上组合或合并JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!