创建一个JavaScript对象,用于获取每个数组项并对其进行整理
我试图创建一个JavaScript对象,该对象获取BusinessData中的每个创建一个JavaScript对象,用于获取每个数组项并对其进行整理,javascript,angularjs,Javascript,Angularjs,我试图创建一个JavaScript对象,该对象获取BusinessData中的每个服务数组,然后按如下方式对其进行整理: services: [ { id: 1, businessId: 1, title: 'Brake Fluid Refresh' }, {
服务
数组,然后按如下方式对其进行整理:
services: [
{
id: 1,
businessId: 1,
title: 'Brake Fluid Refresh'
},
{
id: 2,
businessId: 1,
title: 'Diagnostics'
},
{
id: 3,
businessId: 1,
title: 'Coolant Refresh'
},
{
id: 4,
businessId: 1
title: 'Oil Change'
},
{
id: 5,
businessId: 1,
title: 'MOT'
},
{
id: 6,
businessId: 1,
title: 'Summer Check'
},
{
id: 7,
businessId: 1,
title: 'Winter Check'
}
]
这是我目前的代码:
var businessData = [
{
id: 1,
categoryId: 1,
name: 'Japan Center Garage',
services: [
{
id: 1,
businessId: 1,
title: 'Brake Fluid Refresh'
},
{
id: 2,
businessId: 1,
title: 'Diagnostics'
}
]
},
{
id: 2,
categoryId: 1,
name: 'Rex Garage',
services: [
{
id: 3,
businessId: 1,
title: 'Coolant Refresh'
},
{
id: 4,
businessId: 1
title: 'Oil Change'
}
]
},
{
id: 3,
categoryId: 1,
name: 'Mission & Bartlett Garage',
services: [
{
id: 5,
businessId: 1,
title: 'MOT'
},
{
id: 6,
businessId: 1,
title: 'Summer Check'
},
{
id: 7,
businessId: 1,
title: 'Winter Check'
}
]
}
]
return {
getAllCategories: function () {
return categoryData;
},
getAllServices: function () {
var servicesData = {
services: []
};
for(var i = 0; i < businessData.length; i++) {
if(businessData[i].services) {
servicesData['services'].push(businessData[i].services)
}
}
return servicesData;
},
getAllBusinesses: function () {
return businessData;
},
}
}])
谁能告诉我出了什么问题吗
var services = [];
businessData.forEach(function (business) {
Array.prototype.push.apply(services, business.services);
});
您就快到了,但您正在将服务数组推送到一个数组中。通过使用Array.prototype.push.apply,我们将服务推送到一个数组中。这最终会给你想要的结果:)你可以使用lodash,你最好将它添加到你的工具箱中 以下是它的外观: 甚至
_.flatMap(businessObject, "services")
为了让它更详细一点,您正在进行映射,然后将其展平:
var mapped = _.map(businessObject, "service")
var services = _.flatten(mapped)
在代码中找不到“serviceList”数组。
_.flatMap(businessObject, (d) => d.services)
_.flatMap(businessObject, "services")
var mapped = _.map(businessObject, "service")
var services = _.flatten(mapped)