从对象中提取部分并创建新的简化版本
Extract parts from object and create new reduced version
我有一个 JavaScript 对象,我需要提取其中的一部分,然后创建一个新的对象数组。主要需要注意的是新对象中的键名不同(它是针对 Google 标签管理器的,键名已经预定义)。
我想使用 underscore.js,因为它已经在这个项目中大量使用,但如果 vanilla JS 解决方案更简单,则它不是必需的。
这是现有对象的简化版本
{
'object_handle': 'handle',
'something_else': 'ladela',
'some_other_thing': 'other thing',
'data':{
'object_id': 120,
'buildings':[
{
'item_id':120,
'title':'Some title',
'not_needed': 'Don't need this',
'locations':[
{
'location_id':4444
}
]
},
{
'item_id':121,
'title':'Some other title',
'not_needed': 'Don't need this',
'locations':[
{
'location_id':5555
}
]
},
{
'item_id':122,
'title':'Some different title',
'not_needed': 'Don't need this',
'locations':[
{
'location_id':6666
}
]
}
]
}
}
我想提取部分(来自 data.buildings)并创建这个新对象数组
[{
'name': 'Some title',
'id': '120',
'location': '4444'
},
{
'name': 'Some other title',
'id': '121',
'location': '5555'
},
{
'name': 'Some different title',
'id': '122',
'location': '6666'
}]
如有任何建议,我们将不胜感激。
如果有帮助,我已经用数据创建了一个 Fiddle - https://jsfiddle.net/e7t8ypmd/2/
试试这个...
我认为 var a 是你的对象...
var a ={your object};
var b = _.each(a.data.buildings, function (item) {
item.name = item.title;
item.id = item.item_id;
item.location = item.locations[0].location_id;
});
var plucked = b.map(function (model) {
return _.pick(model, ["name", "id","location"]);
});
变量 'plucked' 将仅具有必需的属性。
我有一个 JavaScript 对象,我需要提取其中的一部分,然后创建一个新的对象数组。主要需要注意的是新对象中的键名不同(它是针对 Google 标签管理器的,键名已经预定义)。
我想使用 underscore.js,因为它已经在这个项目中大量使用,但如果 vanilla JS 解决方案更简单,则它不是必需的。
这是现有对象的简化版本
{
'object_handle': 'handle',
'something_else': 'ladela',
'some_other_thing': 'other thing',
'data':{
'object_id': 120,
'buildings':[
{
'item_id':120,
'title':'Some title',
'not_needed': 'Don't need this',
'locations':[
{
'location_id':4444
}
]
},
{
'item_id':121,
'title':'Some other title',
'not_needed': 'Don't need this',
'locations':[
{
'location_id':5555
}
]
},
{
'item_id':122,
'title':'Some different title',
'not_needed': 'Don't need this',
'locations':[
{
'location_id':6666
}
]
}
]
}
}
我想提取部分(来自 data.buildings)并创建这个新对象数组
[{
'name': 'Some title',
'id': '120',
'location': '4444'
},
{
'name': 'Some other title',
'id': '121',
'location': '5555'
},
{
'name': 'Some different title',
'id': '122',
'location': '6666'
}]
如有任何建议,我们将不胜感激。
如果有帮助,我已经用数据创建了一个 Fiddle - https://jsfiddle.net/e7t8ypmd/2/
试试这个...
我认为 var a 是你的对象...
var a ={your object};
var b = _.each(a.data.buildings, function (item) {
item.name = item.title;
item.id = item.item_id;
item.location = item.locations[0].location_id;
});
var plucked = b.map(function (model) {
return _.pick(model, ["name", "id","location"]);
});
变量 'plucked' 将仅具有必需的属性。