我从服务器获得了一个差异对象,需要将其合并到本地表示中。 因此,我需要一种方法来添加当前在原始表示中 undefined object 部分。
示例:
// The serverresponse
{
"PRIVATE": {
"SCREENS": {
"WORKSPACE": {
"POSTS": {
"1363391397125": {
"TGT": "1363390641817",
"ACN": "position",
"TO": [
57.1875,
69.21182266009852
]
}
}
}
}
}
}
// This part is similar to my local representation
{
"PRIVATE": {
"SCREENS": {
"WORKSPACE": {
"POSTS": {}
}
}
}
// So I want to insert this part of the given data at same position inside the local data
{
"1363391397125": {
"TGT": "1363390641817",
"ACN": "position",
"TO": [
57.1875,
69.21182266009852
]
}
}
需要插入很多不同的部分,因此我正在寻找明确的替代方案来迭代我将拥有的每种情况。
最佳答案
看到您添加了 jQuery 标签,您可以使用 jQuery 的 extend()方法,类似如下:
// The serverresponse
var x = {
"PRIVATE": {
"SCREENS": {
"WORKSPACE": {
"POSTS": {
"1363391397125": {
"TGT": "1363390641817",
"ACN": "position",
"TO": [
57.1875,
69.21182266009852]
}
}
}
}
}
};
// This part is similar to my local representation
var y = {
"PRIVATE": {
"SCREENS": {
"WORKSPACE": {
"POSTS": {}
}
}
}
};
// merges x into y
$.extend(y, x);
// use $.extend(x, y); if you intended it to be the other way around.
<小时/>
DEMO - 使用 $.extend()
合并对象。
关于javascript - 将对象差异添加到 "right"位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444024/