I am trying to create a JavaScript object that grabs each services array in BusinessData, and then collates it as follows:
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'
}
]
This is my code so far:
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;
},
}
}])
It doesn't work very well, and produced an array that I can't seem to access in my view after calling it from my controller:
<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>
Update
serviceList is called from my the controller:
$scope.serviceList = ServicesData.getAllServices();
What is going wrong here?
var services = [];
businessData.forEach(function (business) {
Array.prototype.push.apply(services, business.services);
});
You are almost there, but you are pushing array of services to an array. By using Array.prototype.push.apply, we are instead pushing services to an array. Which eventually gives you the result you want :)
You can use lodash for that, and you better add it to your toolkit in general.
Here is how it will look with lodash:
_.flatMap(businessObject, (d) => d.services)
Or even
_.flatMap(businessObject, "services")
To make it little bit more verbose, you are doing map and then flatten:
var mapped = _.map(businessObject, "service")
var services = _.flatten(mapped)
Related
When I click the button, I want to include all the objects in the itemSold and itemGet objects of the customers into the products array. how can I do that?
let customers = [{
active: true,
id: 1,
product: {
itemSold: [{id:1,name : 'car'}, {id:2,name : 'home'}],
itemGet: [{id:3,name : 'phone'}, {id:4,name : 'fly'}],
},
},
{
active: true,
id: 2,
product: {
itemSold: [{id:5,name : 'lamb'}, {id:6,name : 'mouse'}],
itemGet: [{id:7,name : 'mouse pad'}, {id:8,name : 'tv'}],
},
},
];
let clickButton = document.querySelector("#clickButton");
let products = [];
clickButton.addEventListener("click", getProcuts()});
function getProducts(){}
<button id="clickButton" >Click
</button>
let customers = [{
active: true,
id: 1,
product: {
itemSold: [{ id: 1, name: 'car' }, { id: 2, name: 'home' }],
itemGet: [{ id: 3, name: 'phone' }, { id: 4, name: 'fly' }],
},
},
{
active: true,
id: 2,
product: {
itemSold: [{ id: 5, name: 'lamb' }, { id: 6, name: 'mouse' }],
itemGet: [{ id: 7, name: 'mouse pad' }, { id: 8, name: 'tv' }],
},
},
];
let clickButton = document.querySelector("#clickButton");
let products = [];
clickButton.addEventListener("click", getProducts);
function getProducts() {
for (let i = 0; i < customers.length; i++) {
products.push(...customers[i].product.itemGet, ...customers[i].product.itemSold);
}
console.log(products);
}
<button id="clickButton">Click</button>
We loop our customers array and then select product property there we push both itemSold and itemGet arrays into products.
You can map over the customers and concatenate the arrays.
const customers = [
{
active: true,
id: 1,
product: {
itemSold: [
{ id: 1, name: "car" },
{ id: 2, name: "home" },
],
itemGet: [
{ id: 3, name: "phone" },
{ id: 4, name: "fly" },
],
},
},
{
active: true,
id: 2,
product: {
itemSold: [
{ id: 5, name: "lamb" },
{ id: 6, name: "mouse" },
],
itemGet: [
{ id: 7, name: "mouse pad" },
{ id: 8, name: "tv" },
],
},
},
];
const products = customers.map((customer) => {
return customer.product.itemSold.concat(customer.product.itemGet);
});
console.log(products);
const customers = [
{
active: true,
id: 1,
product: {
itemSold: [
{ id: 1, name: "car" },
{ id: 2, name: "home" },
],
itemGet: [
{ id: 3, name: "phone" },
{ id: 4, name: "fly" },
],
},
},
{
active: true,
id: 2,
product: {
itemSold: [
{ id: 5, name: "lamb" },
{ id: 6, name: "mouse" },
],
itemGet: [
{ id: 7, name: "mouse pad" },
{ id: 8, name: "tv" },
],
},
},
];
const products = customers.map((customer) => {
return customer.product.itemSold.concat(customer.product.itemGet).flat();
});
console.log(products.flat());
I have an array of Objects
const options = [
{ id: 1, name: "Back Pain" },
{ id: 2, name: "Body aches" },
{ id: 3, name: "Cold Sores" },
{ id: 4, name: "Cough" },
{ id: 5, name: "Constipation" },
];
I am trying to write a function that will assign new properties to the object.
The output I am looking for is:
const options = [
{ value: 1, label: "Back Pain" },
{ value: 2, label: "Body aches" },
{ value: 3, label: "Cold Sores" },
{ value: 4, label: "Cough" },
{ value: 5, label: "Constipation" },
];
I have tried to loop through the array using a for loop, but can not figure it out.
Thanks for the help:)
You can do it like this:
const data=[{ id: 1, name: "Back Pain" },
{ id: 2, name: "Body aches" },
{ id: 3, name: "Cold Sores" },
{ id: 4, name: "Cough" },
{ id: 5, name: "Constipation" },
];
var result = data.map(({id:value, name:label})=>({value, label}));
console.log(result);
I have two JSON objects: I need to substitute the values from the properties from the product JSON with values from the properties from the branch JSON.
This is about plain JavaScript.
I have tried it with map and filter but the problem is that when there is no brand for a certain product the application crashes and that should be prevented. I also tried it with map and if's see JSFiddle link below.
var product = {
products: [{
ID: 1,
brandDescr: 'substitute', //this value should be substituded with the branch Description
brandID: 1,
colorCode: 2,
colorDesc: 'substitute',
},
{
ID: 2,
brandDescr: 'substitute',
brandID: 2,
colorCode: 3,
colorDesc: 'substitute',
},
{
ID: 3,
brandDescr: 'substitute',
brandID: 12,
colorCode: 3,
colorDesc: 'substitute',
}
]
}
var brand = {
brands: [{
Description: 'BMW',
ID: 1
},
{
Description: 'Mercedes',
ID: 2
},
{
Description: 'Audi',
ID: 3
},
]
}
/**mthis method crashes when there is no Description for a Brand.
*for example for product ID 3 there is no brand description because brandID
* 12 does not exist
*/
product.products.forEach((x) => {
x.brandDescr = brand.brands.filter(function (y) {
console.log('Value: ' + x.brandID + y.ID)
return x.brandID == y.ID
})[0].Description
});
So the result should be that the brandDescr in product should be substituted with the Description from brand and when there is no matching Description in brand the application should not crash.
And because performance is an issue, it should be prevented to do a double filter: the first time to check if the array is not empty, so to check if there is a branchDescr available for a product and the second time to do the actual substitution.
I have created a JSFiddle at
https://jsfiddle.net/Ben197/wpcz21e7/88/
var product = {
products: [{
ID: 1,
brandDescr: 'substitute', //this value should be substituded with the branch Description
brandID: 1,
colorCode: 2,
colorDesc: 'substitute',
},
{
ID: 2,
brandDescr: 'substitute',
brandID: 2,
colorCode: 3,
colorDesc: 'substitute',
},
{
ID: 3,
brandDescr: 'substitute',
brandID: 12,
colorCode: 3,
colorDesc: 'substitute',
}
]
}
var brand = {
brands: [{
Description: 'BMW',
ID: 1
},
{
Description: 'Mercedes',
ID: 2
},
{
Description: 'Audi',
ID: 3
},
]
}
product.products.forEach(productItem => {
const maybeBrand = brand.brands.find(i => i.ID === productItem.brandID);
if (maybeBrand) {
productItem.brandDescr = maybeBrand.Description;
}
});
console.log(product.products);
Instead of filter() you can use find() and instead of getting the first element (i.e.: ...[0].Description) you can use a different way to save the value:
product.products.forEach(function(ele, idx) {
var descr = brand.brands.find((currele) => currele.ID == ele.brandID);
// if descr is not undefined use descr.Description else use the default...
ele.brandDescr = descr && descr.Description || ele.brandDescr;
});
var product = {
products: [{
ID: 1,
brandDescr: 'substitute', //this value should be substituded with the branch Description
brandID: 1,
colorCode: 2,
colorDesc: 'substitute'
},
{
ID: 2,
brandDescr: 'substitute',
brandID: 2,
colorCode: 3,
colorDesc: 'substitute'
},
{
ID: 3,
brandDescr: 'substitute',
brandID: 12,
colorCode: 3,
colorDesc: 'substitute'
}
]
}
var brand = {
brands: [{
Description: 'BMW',
ID: 1
},
{
Description: 'Mercedes',
ID: 2
},
{
Description: 'Audi',
ID: 3
},
]
}
product.products.forEach(function(ele, idx) {
var descr = brand.brands.find((currele) => currele.ID == ele.brandID);
ele.brandDescr = descr && descr.Description || ele.brandDescr;
});
console.log(product);
Here is a simple snippet. This will work as you are wishing.
product.products.forEach((x) => {
brand.brands.map(e=>{
if(e.ID == x.brandID){
product.products[x.ID-1].brandDescr = e.Description;
}
})
});
console.log(product.products);
I need to create a nested json object from a node-mysql results (json objects) here is what I'm trying to acomplish
Those are the mysql json objects that I have:
plants:
[{id: 1, name: 'plant 1'},
{id: 2, name: 'plant 2'}]
areas:
[{id: 1, nombre: 'area 1', plants_id: 1 },
{ id: 2, nombre: 'area 1 - plant 2', plantas_id: 2 },
{ id: 3, nombre: 'area n', plantas_id: 1 }]
machines:
[{id: 1, nombre: 'machine 1 - area 1', areas_id: 1 },
{ id: 2, nombre: 'machine 1 - area 2', areas_id: 2 },
{ id: 3, nombre: 'machine n', areas_id: 2 }]
And this the json that I need to create with the values of the previous json:
{
"plants":[
{
"name":"plant 1",
"areas": [
{ "name":"area 1",
"machines":[
{"nombre":"machine 1 - area 1"
}]
},
{ "nombre":"area 2",
"machines":[
{"nombre":"machine 1 - area 2"
}]
}
]
},
{
"name":"plant 2",
"areas": [
{ "nombre":"area 1 - plant 2",
"maquinas":[ ]
}
]
}
]
}
I've been trying with nested for loops but it's a mess, I read about linq but I have never worked with it
Sorry for the bad english. Any help is appreciated
Thanks and regards
This isn't an efficient solution but if your dataset is small, it works.
var plants = [
{ id: 1, name: 'plant 1' },
{ id: 2, name: 'plant 2' },
];
var areas = [
{ id: 1, nombre: 'area 1', plantas_id: 1 }, // there was a spelling mistake here
{ id: 2, nombre: 'area 1 - plant 2', plantas_id: 2 },
{ id: 3, nombre: 'area n', plantas_id: 1 },
];
var machines = [
{ id: 1, nombre: 'machine 1 - area 1', areas_id: 1 },
{ id: 2, nombre: 'machine 1 - area 2', areas_id: 2 },
{ id: 3, nombre: 'machine n', areas_id: 2 },
];
console.time('result');
function result() {
return plants.map(function(plant) {
return {
"name": plant.name,
"areas": areas.filter(function(area) {
return area.plantas_id == plant.id;
}).map(function(area) {
return {
"nombre": area.nombre,
"machines": machines.filter(function(machine) {
return machine.areas_id == area.id;
}).map(function(machine) {
return {
"nombre": machine.nombre,
};
}),
};
}),
};
});
}
console.timeEnd('result');
console.log(result());
I am trying to get this array from a remote server which is connected to a dynamic database of course.
As far as i read from ionic forums i need to use $http function from AngularJS but i am pretty new to AngularJS and current examples seems too much complicated to me like this one.
I am trying to convert this example to Remote JSON.
HTML Part:
<ion-list>
<ion-item ng-repeat="item in items"
item="item"
href="#/item/{{item.id}}">
Person {{ item.id }} Name {{ item.name }}
</ion-item>
</ion-list>
Array Part:
var friends = [
{ id: 1, name: 'G.I. Joe' },
{ id: 2, name: 'Miss Frizzle' },
{ id: 3, name: 'Scruff McGruff' },
{ id: 4, name: 'G.I. Joe' },
{ id: 5, name: 'Miss Frizzle' },
{ id: 6, name: 'Scruff McGruff' },
{ id: 7, name: 'G.I. Joe' },
{ id: 8, name: 'Miss Frizzle' },
{ id: 9, name: 'Scruff McGruff' },
{ id: 10, name: 'G.I. Joe' },
{ id: 11, name: 'Miss Frizzle' },
{ id: 12, name: 'Scruff McGruff' },
{ id: 13, name: 'G.I. Joe' },
{ id: 14, name: 'Miss Frizzle' },
{ id: 15, name: 'Scruff McGruff' },
{ id: 16, name: 'G.I. Joe' },
{ id: 17, name: 'Miss Frizzle' },
{ id: 18, name: 'Ash Ketchum' }
];
I have tried:
$scope.items = jsonp('http://www.garsoncepte.com/json.php');
$scope.items = $http.jsonp('http://www.garsoncepte.com/json.php');
var url = "http://www.garsoncepte.com/json.php";
$scope.items = $http.jsonp(url);
Since you're using jsonp, You will need set callback function to JSON_CALLBACK and set your items in callback functions.
$scope.items = [];
var url = "http://www.garsoncepte.com/json.php?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data) {
$scope.items = data;
});
= DEMO =
http://plnkr.co/edit/SyMNFBukQsE9B8WQ9Icv?p=preview