How to access a single object from a JSON array - angularjs

Okay so I have a JSON:
{
"Concepts": [
{
"Concept": "1",
"Description": "siopao"
},
{
"Concept": "4",
"Description": "gulaman"
},
{
"Concept": "9",
"Description": "sisig"
},
{
"Concept": "12",
"Description": "noodle"
},
{
"Concept": "15",
"Description": "sisigan"
},
{
"Concept": "16",
"Description": "buko shake"
},
{
"Concept": "17",
"Description": "mango shake"
},
{
"Concept": "19",
"Description": "burger"
},
{
"Concept": "20",
"Description": "sample"
},
{
"Concept": "21",
"Description": "shit"
}
]
}
How do I get only "Description":"siopao"? I'm using AngularJS.

If you want to map the jsonstring to something like:
["siopao", "gulaman", "sisig", "noodle", "sisigan", "buko shake", "mango shake", "burger", "sample", "shit"]
use
var object = JSON.parse(jsonString);
var descriptions = object.Concepts.map(function(c) {
return o.Description;
});
If you only want the one with the description "siopao", add a filter before the map:
var object = JSON.parse(jsonString);
var description = object.Concepts.filter(function(a) {
return a.Description === "siopao";
}).map(function(c) {
return o.Description;
})[0];

Related

How to iterate object when it contains array of objects?

Input :
{
"id": "123",
"address": [{
"street": "5",
"city": "ameerpet",
"pin": "500073"
}, {
"street": "6",
"city": "sec",
"pin": "500020"
}]
}
Note: ["LAA001","LAA002","LAA003"] -> use this as a variable
Required output:
[{
"id": "123",
"lob": "LAA001",
"attributeText": "5"
},
{
"id": "123",
"lob": "LAA001",
"attributeText": "6"
},
{
"id": "123",
"lob": "LAA002",
"attributeText": "ameerpet"
},
{
"id": "123",
"lob": "LAA002",
"attributeText": "sec"
},
{
"id": "123",
"lob": "LAA003",
"attributeText": "500073"
},
{
"id": "123",
"lob": "LAA003",
"attributeText": "500020"
}
]
If you are using JavaScript, that should work:
var input = { "id": "123", "address": [ { "street": "5", "city": "ameerpet", "pin": "500073" }, { "street": "6", "city": "sec", "pin": "500020" }] }
var iob = ["LAA001","LAA002","LAA003"]
var output = []
input['address'].forEach((item, index) => {
var keyIndex = 0
for(const key in item){
let obj = {
"id": input['id'],
"lob": iob[keyIndex],
"attributeText": item[key]
}
output.push(obj)
keyIndex += 1
}
%dw 2.0
output application/json
var inp = ["LAA001","LAA002","LAA003"]
var inp1 = payload.address.street ++ payload.address.city ++ payload.address.pin
---
inp1 map {
id: payload.id,
lob: inp[(($$)/2)],
attributeText: $
}

how to map and array inside of an object

So here I have an object that I am trying to map:
var bakery = {
"items":
{
"item":[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter":[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
...
...
...
]
}
}
This is the target outcome
var target = [{
"id": 1, //as an int
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": "all of the batter types as a string",
"ingredients": [],//a copy of all the toppings
"countOfFillings": 0
}];
And here is my mapping function
// creates variable bakeryArray that contains the actual Array inside of Baker var
var bakeryArray = bakery.items.item
// newCakes var invoked map function with the bakeryArray
var newCakes = bakeryArray.map(mapCakes)
function mapCakes(oldCakes) {
let batter = oldCakes.batters.batter
console.log(batter, "batter Logged")
var newCakesObject = {
type: oldCakes.type,
name: oldCakes.name,
ppu: oldCakes.ppu,
batters: batter.type,
ingredients: "ingridients",
countOfFillings: "total number of ingrediensts"
};
return newCakesObject;
};
I am running into problems in getting the Batter, Ingredients, and countOfFillings from the old object into the new one.
The only thing I can think of doing in order to get the batters in the newCakesObject is that I have to create another mapping function for the batter (I put my attempt at that below)? and then invoke that in the mapCakes function under batters? but every time I create another function for that I get an error saying that it's undefined once I call newBatterArray in the console
var newBatterArray = bakeryArray.map(mapBatters)
function mapBatters(oldarray) {
let theBatters = oldarray.batters.batter
console.log(theBatters.type, "we ran")
var newBatters = {
type: theBatters.type
}
return newBatters;
}
To have a much more clear interpretation of your bakery object I have tweaked it a bit
var bakery = {
"items":[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
],
"toppings":[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Cake",
"ppu": 0.65,
"batters":[
{ "id": "1001", "type": "Regular1" },
{ "id": "1002", "type": "Chocolate1" },
{ "id": "1003", "type": "Blueberry1" },
{ "id": "1004", "type": "Devil's Food1" }
],
"toppings":[
{ "id": "5001", "type": "None1" },
{ "id": "5002", "type": "Glazed1" },
{ "id": "5005", "type": "Sugar1" },
{ "id": "5007", "type": "Powdered Sugar1" },
{ "id": "5006", "type": "Chocolate with Sprinkles1" },
{ "id": "5003", "type": "Chocolate1" },
{ "id": "5004", "type": "Maple1" }
]
},
...
...
...
...
]
}
Now You can iterate through each item and build your target array as follows
var target = [];
// define reducer function for each item in bakery.items
const reduceToTarget = item => {
var obj = {};
obj.id = item.id;
obj.type = item.type;
obj.name = item.name;
obj.ppu = item.ppu;
obj.batters = '';
item.batters.forEach(b => obj.batters+=b.type+'|');
obj.ingredients = item.toppings;
target.push(obj);
}
// Now you can call the reduceToTarget function to get the desired target list/array
bakery.items.forEach(reduceToTarget);
The output for this looks something like this
target = [
{
id: "0001"
type: "donut"
name: "Cake"
ppu: 0.55
batters: "Regular|Chocolate|Blueberry|Devil's Food|",
ingredients : [/* list of ingredients*/]
},
{
id: "0002"
type: "donut"
name: "Cake"
ppu: 0.65
batters: "Regular|Chocolate|Blueberry|Devil's Food|",
ingredients : [/* list of ingredients*/]
}
]
NOTE:
For getting the countOfFillings you can simply call length() function on your ingredients list for any element in target

React. Running .map or .filter inside another map

How do you run a map or filter inside another map? I have some Json with a menu. And I want to loop true the Json and se if my first level has any childs. And return a bootstrap dropdown if they have a child, and normal button if not. And then loop true all childs if there is any. . . . . . . . . . . . . . . . .
import React from 'react';
// MockData
var MockData = [
{
"text": "Chocolate Beverage",
"id": "1",
"parentid": "-1"
}, {
"id": "2",
"parentid": "1",
"text": "Hot Chocolate"
}, {
"id": "3",
"parentid": "1",
"text": "Peppermint Hot Chocolate"
}, {
"id": "4",
"parentid": "1",
"text": "Salted Caramel Hot Chocolate"
}, {
"id": "5",
"parentid": "1",
"text": "White Hot Chocolate"
}, {
"id": "6",
"text": "Espresso Beverage",
"parentid": "-1"
}, {
"id": "7",
"parentid": "6",
"text": "Caffe Americano"
}, {
"id": "8",
"text": "Caffe Latte",
"parentid": "6"
}, {
"id": "9",
"text": "Caffe Mocha",
"parentid": "6"
}, {
"id": "10",
"text": "Cappuccino",
"parentid": "6"
}, {
"id": "11",
"text": "Pumpkin Spice Latte",
"parentid": "6"
}, {
"id": "12",
"text": "Frappuccino",
"parentid": "-1"
}, {
"id": "13",
"text": "Caffe Vanilla Frappuccino",
"parentid": "12"
}, {
"id": "15",
"text": "450 calories",
"parentid": "13"
}, {
"id": "16",
"text": "16g fat",
"parentid": "13"
}, {
"id": "17",
"text": "13g protein",
"parentid": "13"
}, {
"id": "14",
"text": "Caffe Vanilla Frappuccino Light",
"parentid": "12"
}]
export default class Test2 extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
showSubMenu: []
};
}
render() {
var children = {};
for (let obj of MockData) {
if (!children.hasOwnProperty(obj.parentid)) {
children[obj.parentid] = [obj.id];
}
else {
children[obj.parentid].push(obj.id);
}
}
const map_func = (firstLevel, index) => {
if (children.hasOwnProperty(firstLevel.id)) {
return <p><b>Dropdown / {firstLevel.text} / {firstLevel.parentid}</b></p>;
} else {
return <p>Button / {firstLevel.text} / {firstLevel.parentid}</p>;
}
};
return (
<div>
{MockData.map(map_func)}
</div>
);
}
}
You should just build a map like:
var children = {};
for (let obj of MockData) {
if (!children.hasOwnProperty(obj.parentid)) {
children[obj.parentid] = [obj.id];
}
else {
children[obj.parentid].push(obj.id);
}
}
Now you can easily check if your firstLevel has at least one child this way:
if (children.hasOwnProperty(firstLevel.id)) {
// bootstrap dropdown
} else {
// normal button
}
And the children ids are in children[firstLevel.id] if there are any
Edit: So your final code should look like this:
render() {
const map_func = (firstLevel, index) => {
if (children.hasOwnProperty(firstLevel.id)) {
// return bootstrap dropdown;
} else {
// return normal button;
}
};
return (
<div>
{MockData.map(map_func)}
</div>
);
}

DataTables - Load data from pre-defined JSON

I have a problem pointing dataTable to the right spot in the JSON. I receive a nested array:
{
"status": "ok",
"count": "7",
"msg ": "Operation Successful",
"data": [{
"contactHasServiceArea": true,
"issueCategories": [{
"id": "8",
"description": "Finance"
},
{
"id": "9",
"description": "Housing"
},
{
"id": "10",
"description": "International"
}
],
"cases": [{
"id": 31645,
"client_name": "Matthew",
"issue": "Assessment Completion",
"referral": null,
"opened_date": "10\/07\/2017",
"case_status": "Open"
}, {
"id": 31668,
"client_name": "Fanky ",
"issue": "Complex",
"referral": null,
"opened_date": "01\/07\/2017",
"case_status": "Open"
}]
}]
}
How do I point to the "cases" object? I'm sure this is simply, but I'm confused by the many options in the dataTables config.
I tried variations of data, dataSrc as well as data.cases or just cases, etc.
Thanks
$('#cases_table').DataTable( {
"ajax": "ajax/getCases",
"dataSrc" : "data.cases",
"data" : "cases",
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
You can configure like this:
$('#cases_table').DataTable( {
"ajax": {
"url": "ajax/getCases",
"dataSrc" : "data.cases"
},
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
datasrc points into the returns json. Remove the data option.

AngularJS multiple Scope needed for Autocomplete

I have an array structure like this.
[
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
I need $scope like below for my autocomplete search.
$scope.name=["john","Gerold","Stuart"];
$scope.city=["NY","LA","Boston"];
can anyone help to get this using angularjs controller.
Thanks in Advance.!
Use MAP
$scope.users = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
];
$scope.cities = $scope.users.map(function(obj){
return obj.city;
});
console.log($scope.cities);
You can also create a helper function that would do that for you and you don't have to define a map per function that you want, and you do it in just one run (hence just a bit faster)
Sample here ;)
var myArray = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
function toScope(scopedPropertieNames, array) {
scopedPropertieNames.forEach(function(propertyName) {
if (! $scope[propertyName]) {
$scope[propertyName] = []
}
});
array.forEach(function (objecInArray) {
scopedPropertieNames.forEach(function(propertyName) {
$scope[propertyName].push(objecInArray[propertyName])
})
});
}
toScope(['name', 'city'], myArray);
console.log($scope) //{name: Array[3], city: Array[3]}
You can use MAP..
$scope.YourBigArray = [{
"id": "1",
"name": "John",
"city": "NY"
}, {
"id": "2",
"name": "Gerold",
"city": "LA"
}, {
"id": "3",
"name": "Stuart",
"city": "Boston"
}];
$scope.names = $scope.YourBigArray.map(function(object) {
return object.name;
});
$scope.cities = $scope.YourBigArray.map(function(object) {
return object.city;
});
You can do a filter to use unique things in array of names and cities..
function filterForDuplicate(things) {
return things.filter(function(item, pos) {
return things.indexOf(item) === pos;
});
}

Resources