I have below object which I am currently looping through in number of different functions to get an item with name or setting a new value.(我下面有一个对象,该对象当前正在许多不同功能中循环显示,以获取具有名称的项目或设置新值。)
Currently I am using lodash _.foreach and ._map to achieve both actions.(目前,我正在使用lodash _.foreach和._map来完成这两个动作。) I know lodash has function such as _.filter however I am unable to get it to work with the object that I have.(我知道lodash具有_.filter之类的功能,但是我无法使其与我拥有的对象一起使用。)
let data = [
{
"panels" : [
{
"title": "Panel 1",
"items" : [
{
"name": item1,
"value": 1
}
{
"name": item2,
"value": 2
}
]
},
{
"title": "Panel 2",
"items" : [
{
"name": item3,
"value": 3
}
{
"name": item4,
"value": 5
}
]
}
]
}
{
"panels" : [
{
"title": "Panel 3"
"items" : [
{
"name": item5,
"value": 5
}
{
"name": item6,
"value": 6
}
]
}
]
}
{
"panels" : [
{
"title": "Panel 4"
"items" : [
{
"name": item7,
"value": 7
}
{
"name": item8,
"value": 8
}
]
}
]
}
]
// Get item from the object with given name
getItem: function(name) {
let item = false;
_.forEach(data, function (group) {
_.forEach(group.panels, function (panel) {
_.forEach(panel.items, function (item) {
if (item.name == name) {
filterItem = item;
return false;
}
});
});
});
return item ;
},
//Set item new value
updateItemValue (name, value) {
_.map(data, function(group) {
_.map(group.panels, function(panel) {
_.map(panel.items, function(item) {
if( item.name === name ) {
item.value = value;
}
});
});
});
}
Is there any other way I can achieve this in more efficient way ?(我还有其他方法可以更有效地实现这一目标吗?)
ask by user4676307 translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…