我有一个对象A.
如果我JSON.stringify(A)
,我得到这个结果:
{
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}]
}
现在,我想克隆它自己的元素并创建一个更大的对象:
{
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}],
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}],
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}]
}
如何使用lodash / underscore /或jQuery实现这一目标?
到目前为止,我已经尝试过jQuery.extend,lodash union,并且没有工作。
答案 0 :(得分:1)
您无法创建您描述的对象。您在每种情况下重复属性名称"OrderA"
,这是不允许的。我建议使用一个新数组并将对象推入内部,而不是具有属性名称的映射对象。像这样粗糙的东西:
var A; //Your OrderA Object.
var B = jQuery.extend(true, {}, A),
C = jQuery.extend(true, {}, A),
D = jQuery.extend(true, {}, A);
var arr = [A, B, C, D];
答案 1 :(得分:0)
我认为你需要使用不同的密钥,但这不会起作用吗?
var A = {
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}]
};
var B = {};
for (var attr in A.OrderA[0]) {
if (A.OrderA[0].hasOwnProperty(attr)) {
B[attr] = A.OrderA[0][attr];
}
}
A.OrderB = [B];
JSON.stringify(A);
{
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}],
"OrderB": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}]
}
答案 2 :(得分:0)
对象键必须是唯一的,否则您将覆盖以前保存的数据。请参阅DEMO。
以下是:
var ALL = {
"OrderA": [{
"orderId": "19",
"serverId": 129,
"description": "Apple",
"status": "1",
"details": ""
}]
};
['B','C','D'].forEach(function(letter,index) {
ALL['Order'+letter] = $.extend(true, {}, ALL.OrderA);
});
console.log( JSON.stringify( ALL ) );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;