2017-02-28 80 views
1

我知道有一些类似的问题,但其中的非不由我与我的问题:更新JavaScript对象

我有一个对象:

var mapOptions = { 
     legend: { 
      data:[ 
       {name: 'Europe', backgroundColor: 'RGB(228,101,41)'}, 
       {name: 'APAC', backgroundColor: 'RGB(0,71,126)'}, 
       {name: 'MENEAT', backgroundColor: 'RGB(145,0,73)'} 
      ], 
     } 
    } 

这个对象应该通过这个对象进行更新:

var newOptions = { 
      legend: { 
      data: [ 
       {name: 'Europe', backgroundColor: 'green'}, 
      ] 
      } 
    } 

应该更新功能能够做什么:

  1. 更新属性:从'RGB(228,101,41)''green'

  2. 删除不需要的物品:如只有'Europe'项应该保留。

现在我用的是jQuery extend/deep功能:

$.extend(true, mapOptions, newOptions); 

它的工作原理部分。只有属性被更新。

任何人都可以帮助我实现第二点,如何删除/添加项目?

还是应该把它分成两个函数更好?

谢谢你的帮助!

+0

'更新的属性:从 'RGB(228,101,41)' 到“green''不是所有的RGB值有英文名字。在这种情况下你想做什么? – mehulmpt

+0

@MehulMohan指出第一个问题。第二个问题,基于你想要删除一个项目?你只想保留'欧洲'?如果有多次'欧洲'会怎么样? – Weedoze

+0

1.问题:只是一个例子。我将使用RGBs代替:) –

回答

1

,该解决方案可能是一个基本的任务:

mapOptions.legend.data = newOptions.legend.data 
+0

问题是此对象中存在多个“数据”属性。看起来每个人都必须以基本的分配为基础。感谢帮助 –

1

如果你只想改变第一valeus 你可以使用相对索引位置(0)的数据数组内

mapOptions.legend.data[0] = {name: 'Europe', backgroundColor: 'green'}; 

如果你想改变所有的数据contente,那么你可以使用JavaScript点符号访问基于您的示例对象元素

mapOptions.legend.data = {name: 'Europe', backgroundColor: 'green'}; 
+1

@RoryMcCrossan谢谢回答扩展完整更改 – scaisEdge

0

试试这个

mapOptions.legend.data = {name: 'Europe', backgroundColor: 'green'}; 
0

对多个项目进行更新,你可以使用一个哈希表的对象的引用,然后迭代更新阵列。

如果为给定名称设置了hash,则更新,否则将新对象推送到该数组。

var mapOptions = { legend: { data: [{ name: 'Europe', backgroundColor: 'RGB(228,101,41)' }, { name: 'APAC', backgroundColor: 'RGB(0,71,126)' }, { name: 'MENEAT', backgroundColor: 'RGB(145,0,73)' }], } }, 
 
    newOptions = { legend: { data: [{ name: 'Europe', backgroundColor: 'green' }, ] } }, 
 
    hash = Object.create(null); 
 

 
mapOptions.legend.data.forEach(function (a, i) { 
 
    hash[a.name] = a; 
 
}); 
 

 
newOptions.legend.data.forEach(function (a) { 
 
    if (hash[a.name]) { 
 
     hash[a.name].backgroundColor = a.backgroundColor; 
 
    } else { 
 
     mapOptions.legend.data.push(a); 
 
    } 
 
}); 
 

 
console.log(mapOptions.legend.data);
.as-console-wrapper { max-height: 100% !important; top: 0; }