Add json data to existing array - javascript

I have 2 json files,services.json and services_show.json.At page load am fetching the data from services.json and it working properly.On a button click,i need to fetch the contents from service_show.json and append to the services array but it does not work.
var beautyApp = angular.module('findbeauty', []);
beautyApp.controller('beautycntrl',function($scope,$http){
$http.get('http://localhost/Find-Beauty/media/services.json').success(function(data) {
$scope.services=data.services;
$scope.services1=data.services1;
});
$scope.Add = function(){
$http.get('http://localhost/Find-Beauty/media/services_show.json').success(function(data) {
console.log(angular.toJson(data.services));
$scope.services.push(data.services);
});
};
$scope.ViewMore = function(){
});
Services.json
{
"services":[
{
"name": "Arun",
"gender": "Damen",
"duration": "1.5 Stunden",
"price": "€65,00",
"imagepath": "media/images/prfilepic1.png",
"percentage": "90%"
},
],
"services1":[
{
"name": "Schnitt & Föhnen",
"gender": "Damen",
"duration": "1.5 Stunden",
"price": "€65,00",
"imagepath": "media/images/profilepic4.png",
"percentage": "25%"
},
]
}
service_show.json
{
"services":[
{
"name": "Schnitt & Föhnen",
"gender": "Damen",
"duration": "1.5 Stunden",
"price": "€65,00",
"imagepath": "media/images/profilepic4.png",
"percentage": "5%"
},
],
"services1":[
{
"name": "Schnitt & Föhnen",
"gender": "Damen",
"duration": "1.5 Stunden",
"price": "€65,00",
"imagepath": "media/images/prfilepic1.png",
"percentage": "50%"
},
]
}
How can i push the services_show.json data to $scope.services ? Any Help?

Array.prototype.push.apply() can be used for merging two arrays.
Merge the second array into the first one
$scope.services.push.apply($scope.services, data.services);

You need to push one item at a time, like
angular.forEach(data.services,function(item) {
$scope.services.push(item);
});

You also can use concat:
Here I have my own code: Please refer
$http.get('store/LoadAlbums/', {'iCategoryID': iCategoryID}).then(function (data) {
for (var i = 0; i < $scope.result.mainalbums.length; i++) {
if($scope.result.mainalbums[i].iCategoryID == iCategoryID){
$scope.result.mainalbums[i].albums = $scope.result.mainalbums[i].albums.concat(data.data.albums);
$scope.result.mainalbums[i].totalAlbumCategory = $scope.result.mainalbums[i].albums.concat(data.data.totalAlbumCategory);
$scope.result.mainalbums[i].loadmore = $scope.result.mainalbums[i].albums.concat(data.data.loadmore);
$scope.result.mainalbums[i].newpage = $scope.result.mainalbums[i].albums.concat(data.data.newpage);
}
} });

Related

Push parent arrays element and chidren array into new array in javascript

"items": {
"hotdrinks": [
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 25,
"name": "Coffee",
"img": "../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 50,
"name": "Hot Milk",
"img": "../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 70,
"name": "Horlicks",
"img": "../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
],
}
json i want to achieve using javascript. im just new to handling arrays and objects. thanksfound the answer given by Jeeva which works perfectly
future answers are welcome since we can know diffferent methods to achieve the same json object
dataArray = [
{title:"Hotdrinks",
content: [{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}
You can use like this. This can be achieved by iterating the object.
const data = {
"items":{
"hotdrinks":[
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]
}
}
var dataArray = []
for(k in data.items){
var dataObj = {}
dataObj.title = k
dataObj.content = data.items[k] //You can also access the object values by using bracket ([]) notation
dataArray.push(dataObj)
}
console.log(JSON.stringify(dataArray))
The above expected output json is not valid. We can achieve the following.
[{"title":"Hotdrinks"}, {"content": [
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}]
If you are okay with this then i'll give you the sample code for the same.

how to remove this object from array inside of object in array?

I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]
Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.
#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!
You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");

Push elements dynamically using javascript

I am getting the points from the multidimensional array using map, but I am getting array of array values.
I need the below format:
[36, 122, 25]
But I'm getting the multi array of points.
Below is my code and output
var data = [{
"name": "ramu",
"id": "719",
"gmail": "ramu#gmail.com",
"ph": 988989898,
"points": 36
},
{
"name": "ravi",
"id": "445",
"gmail": "ravi#gmail.com",
"ph": 4554545454,
"points": 122
},
{
"name": "karthik",
"id": "866",
"gmail": "karthik#gmail.com",
"ph": 2332233232,
"points": 25
}
]
var result = data.map(function(arr, count) {
return [arr.points];
});
console.log(result);
output is:
[[36], [122], [25]]
Try below code:
var data = [{"name":"ramu","id":"719","gmail":"ramu#gmail.com","ph":988989898,"points":36},
{"name":"ravi","id":"445","gmail":"ravi#gmail.com","ph":4554545454,"points":122},
{"name":"karthik","id":"866","gmail":"karthik#gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) { return arr.points;});
console.log(result);
var data = [{"name":"ramu","id":"719","gmail":"ramu#gmail.com","ph":988989898,"points":36},
{"name":"ravi","id":"445","gmail":"ravi#gmail.com","ph":4554545454,"points":122},
{"name":"karthik","id":"866","gmail":"karthik#gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) { return arr.points;});
console.log(result);
Remove the [] from return statement. It creates new array and push it to original.
In your code you are using [] that creates a new array using arr.points values. Remove the [] from return statement.
var data = [{
"name": "ramu",
"id": "719",
"gmail": "ramu#gmail.com",
"ph": 988989898,
"points": 36
},
{
"name": "ravi",
"id": "445",
"gmail": "ravi#gmail.com",
"ph": 4554545454,
"points": 122
},
{
"name": "karthik",
"id": "866",
"gmail": "karthik#gmail.com",
"ph": 2332233232,
"points": 25
}
]
var result = data.map(function(arr, count) {
return arr.points;
});
console.log(result);
The function is returning an array of single-element arrays because .map() returns an array, and within each iteration of .map() your function is returning [arr.points] (an element in an array). Change this to return arr.points and you're set.
Also, since you're merely returning a value in the .map() we can simplify the callback function to:
var result = data.map(arr => arr.points);
var data = [{
"name": "ramu",
"id": "719",
"gmail": "ramu#gmail.com",
"ph": 988989898,
"points": 36
},
{
"name": "ravi",
"id": "445",
"gmail": "ravi#gmail.com",
"ph": 4554545454,
"points": 122
},
{
"name": "karthik",
"id": "866",
"gmail": "karthik#gmail.com",
"ph": 2332233232,
"points": 25
}
]
var result = data.map(arr => arr.points);
console.log(result);

Converting into a hierarchical array in javascript

Fiddle Example
I want to convert this JSON data
var data = [
{
"computer": 24,
"brand": "Italy A",
"phone": 0,
"country": "Italy"
},
{
"brand": "Italy C",
"computer": 0,
"phone": 0,
"country": "Italy"
},
{
"brand": "Brazil B",
"computer": 0,
"phone": 22,
"country": "Brazil"
},
{
"computer": 0,
"brand": "Brazil D",
"phone": 62,
"country": "Brazil"
},
{
"computer": 34,
"brand": "US E",
"phone": 41,
"country": "US"
}
];
into a hierarchical form for a d3 graph:
{
"name": "categories",
"children": [
{
"name": "phone",
"children": [
{
"name": "US",
"children": [
{
"brand": "US E",
"size": 41
}
]
},
{
"name": "Brazil",
"children": [
{
"brand": "Brazil B",
"size": 22
},
{
"brand": "Brazil D",
"size": 62
}
]
},
{
"name": "Italy",
"children": []
}
]
},
{
"name": "computer",
"children": [
{
"name": "US",
"children": [
{
"brand": "US E",
"size": 34
}
]
},
{
"name": "Brazil",
"children": []
},
{
"name": "Italy",
"children": [
{
"brand": "Italy A",
"size": 24
}
]
}
]
}
]
}
I came up with this code to generate the format:
function group_children(data){
var categories = ["phone","computer"];
var countries = ["US","Brazil","Italy"];
var object = {name:"categories",children:[]};
for(var c =0; c < categories.length;c++){
object.children.push({"name":categories[c],children:[]});
for(var con = 0;con < countries.length;con++){
object.children[c].children.push({"name":countries[con],"children":[]});
}
}
for(var i = 0;i < data.length;i++){
var row = data[i];
for(var c =0; c < categories.length;c++){
for(var con = 0;con < countries.length;con++){
var cat_key = categories[c],
country_key = countries[con];
if(row[cat_key] > 0){
if(object.children[c].name == cat_key && row.country == country_key){ object.children[c].children[con].children.push({brand:row["brand"],size:row[cat_key]});
}
}
}
}
}
return object;
}
Is it possible , during the iteration, not to push a country into the brand or computer's children array if the country's children array is empty?
For example, these objects should be removed
// computer
{
"name": "Brazil",
"children": []
}
// phone:
{
"name": "Italy",
"children": []
}
Here's the part that push each country into each category's children array:
for(var c =0; c < categories.length;c++){
object.children.push({"name":categories[c],children:[]});
for(var con = 0;con < countries.length;con++){
object.children[c].children.push({"name":countries[con],"children":[]});
}
}
My approach is probably wrong, so any other suggestions converting the data into that hierarchical form is also appreciated.
Check this fiddle, is this what you're looking for? I decided to go for a different approach to the one you followed, hope you don't mind. I've commented the code so that it's clearer:
var result = {
name: "categories",
children: [{
"name": "phone",
"children": []
}, {
"name": "computer",
"children": []
}]
};
$.each(data, function (index, item) {// Go through data and populate the result object.
if (+item.computer > 0) { // Computer has items.
filterAndAdd(item, result.children[1], "computer");
}
if (+item.phone > 0) { // Phone has items.
filterAndAdd(item, result.children[0], "phone");
}
});
function filterAndAdd(item, result_place, type) {// Search and populate.
var i = -1;
$.each(result_place.children, function (index,a) {
if( a.name === item.country ) {
i = index;
return false;
}
});
if (i > -1) {// Country already exists, add to children array.
result_place.children[i].children.push({
"brand": item.brand,
"size": item[type]
});
} else {// Country doesn't exist, create it.
result_place.children.push({
"name": item.country,
"children": [{
"brand": item.brand,
"size": item[type]
}]
});
}
}
Hope it helps.
You have to use d3.nest() function to group array elements hierarchically. The documentation is available
here. Also go through this tutorial which could definitely help you to create hierarchical data.
That's not enough, you get hierarchical data in terms of key and value pairs. But if you want to convert into name and children, already a question on SO is asked, check this.
With your current approach you should iterate the data to find the empty ones, before pushing the countries, which would result in way more iteration than just simply iterating the result at the end to filter the empty ones.
Otherwise you should create the scruture in the same iterations of the data insertion, thus reducing the iterations to 1.

issue with getting JSON child values by specifying full path

I have the below JSON response
{
"r": [{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg":[ {
"Name": "james",
"Rate": 0.05
},
{
"Name": "Jack",
"Rate": 0.55
},
{
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
},
{
"Name": "Jack",
"Rate": 0.55
},
{
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
},
{
"Name": "Jack",
"Rate": 0.55
},
{
"Name": "Mcd",
"Rate": 0.01,
}],
}]
}
I am using $.getJSON method to loads JSON data and adding it in collection by checking whether it is array as below . It is working fine as expected.
var res = loadFromJson(result.r);
loadFromJson = function(input) {
if (_.isArray(input)) {
console.log("Inside Array");
var collection = new CompeCollection();
_.each(input, function(modData) {
collection.add(loadFromJson(modData));
console.log("collection length:"+modData.length);
});
return collection;
}
};
But when i try to specify the exact path(r.Clg) of my JSON response it is not even coming to above if condition though it is valid response.
var res = loadFromJson(result.r.Clg);
loadFromJson = function(input) {
if (_.isArray(input)) {
console.log("Inside Array");
var collection = new CompeCollection();
_.each(input, function(modData) {
collection.add(loadFromJson(modData));
console.log("collection length:"+modData.length);
});
return collection;
}
};
What should i do when i need to specify actual or full path?
Can any one tell me what could be the problem when i pass more specific json values?
Thanks in advance.
result.r.Clg doesn't exist. result.r is an array.
If you only wanted to access the first object in the r array, you would do this:
var res = loadFromJson(result.r);
var clg = res[0].Clg;
Or you could loop over all the objects, perhaps capturing all the Clgs in one array:
var clgs = res.map(function (obj) { return obj.Clg; }, []);

Categories