我有
Range("B25:B" & LastRow).Formula =
"=IFERROR(IF(ISTEXT(E$21),AVERAGEIF(BottomLeftTable[Billing
Name],$A25,BottomLeftTable[Margin]),""""),"""")"
我想形成一个对象/字符串,即以逗号分隔两个对象值。
object1 = {"abc":{"name":"myabcname"}}
object2 = {"def":{"name":"defname"}}
当我尝试{"abc":{"name":"myabcname"},"def":{"name":"defname"}};
时,它会像console.log(JSON.stringify(object1)+JSON.stringify(object2))
答案 0 :(得分:4)
答案 1 :(得分:1)
您可以使用jquery $.extend。
//merging two objects & create new one
var new_object = $.extend({}, object1, object2);
//Merge object2 into object1, recursively
$.extend( true, object1, object2 );
答案 2 :(得分:0)
如果你正在使用jquery,你可以$。扩展第一个对象到第二个。
答案 3 :(得分:0)
如果指定了,JQuery .extend()会将两个对象合并为第三个(除了@Alberto的回答)
// from jQuery docs
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
}
var object3 = {};
$.extend(object3, object1, object2 );
console.log(object3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 4 :(得分:0)
你可以这样:
object1 = {"abc":{"name":"myabcname"}}
object2 = {"def":{"name":"defname"}}
obj = []
obj[Object.keys(object1)[0]] = object1
obj[Object.keys(object2)[0]] = object2
答案 5 :(得分:0)
您可以使用Object.assign
来实现此目标,但是如果您想支持&#34; Internet Explorer&#34; (IE8,IE9,IE10和IE11)您将需要使用此Polyfill:
if (typeof Object.assign != 'function') {
Object.assign = function(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
};
}
参考:MDN
使用:
var obj1 = {"abc":{"name":"myabcname"}};
var obj2 = {"def":{"name":"defname"}};
var mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj);
&#13;
答案 6 :(得分:0)
为了获得您提供的表格形式的字符串,您可以使用:
var object1 = {"abc":{"name":"myabcname"}};
var object2 = {"def":{"name":"defname"}};
var myObject = Object.assing({}, object1, object2);
var myString = JSON.stringify(myObject);
// "{"abc":{"name":"myabcname"},"def":{"name":"defname"}}"
使用Object.assign的危险 - 它只是一个级别的深层复制。 例如:
var me = {
name: "Tomasz",
lastName: "Bubała",
social: {
github: "@tomegz",
twitter: "@tomaszbubala"
}
};
var dev = Object.assign({}, me);
/* This is fine */
dev.name = "Tom";
// => "Tom"
me.name;
// => "Tomasz"
/* This is danger */
dev.social.twitter = "@example";
// => "@example"
me.social.twitter;
// => "@example"
希望在ES7中,您将能够使用传播运营商来实现这一目标:
var myObject = {...object1, ...object2};