创建一个 JavaScript 对象,用于抓取每个数组项并对其进行整理
Creating a JavaScript object that grabs each array item and collates it
我正在尝试创建一个JavaScript对象,该对象抓取BusinessData中的每个services
数组,然后按如下方式对其进行整理:
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;
},
}
}])
它工作得不是很好,并且生成了一个数组,从我的控制器调用它后,我似乎无法访问它:
<div class="item item-divider">
Service
</div>
<ion-list>
<ion-item ng-repeat="item in serviceList | orderBy:'title'">
<p>{{item.title}}</p>
</ion-item>
</ion-list>
<div ng-if="item !== undefined && !item.length" class="no-results">
<div class="item" style="border-top: 0px">
<p>No Results</p>
</div>
</div>
更新
从我的控制器调用serviceList
:
$scope.serviceList = ServicesData.getAllServices();
这里出了什么问题?
var services = [];
businessData.forEach(function (business) {
Array.prototype.push.apply(services, business.services);
});
您几乎就在那里,但您正在将服务数组推送到阵列中。通过使用 Array.prototype.push.apply,我们将服务推送到数组。这最终会给你你想要的结果:)
你可以使用 lodash 来实现这一点,你最好把它添加到你的工具包中。
以下是 lodash 的外观:
_.flatMap(businessObject, (d) => d.services)
甚至
_.flatMap(businessObject, "services")
为了使它更详细一点,您正在执行映射,然后展平:
var mapped = _.map(businessObject, "service")
var services = _.flatten(mapped)
相关文章:
- 取数组,将奇数和偶数推入单独的数组中
- 动态钻取嵌套的对象数组
- Javascript:根据子对象值抓取数组中的对象
- 流星:如何计算每分钟的推文数,而不是所有抓取的推文
- 如何使用Javascript创建Elasticsearch中的索引,其中行名取自数组
- 如何使用jQuery迭代json数组和拉取值
- 如何使用 php 制作正则表达式以从以下代码中抓取复杂数组
- 从对象拉取数组
- 取值更接近的数组
- JavaScript,循环数组,只拉取第一项一次
- Js 数组检测:从 php 数组中找到的值数(从数据库中抓取)
- 创建一个 JavaScript 对象,用于抓取每个数组项并对其进行整理
- 如何从URL中抓取文本并放置在JS数组中
- 一次从数组中取三个元素
- Javascript:在数组中特定值之前和之后抓取值
- 抓取数组中的上一个和下一个元素
- 错误:无法将数组转换为对象数据抓取脚本
- 从具有特定SRC属性的数组中抓取图像
- 使用JSON.parse(),如何在多维数组中取值
- 从输入类型=“”抓取文件时,javascript数组中未定义的文件;文件“;标签