I'm struggling with the following issue:
I have a nested object. From the server I get a response with an object with changed values. So I want to find the object in my nested object and replace it.
My object has a structure like this:
$scope.page = {
id: 5,
label: 'myPage',
items : [
{
"type": "Container",
"id": 1,
"label": "header",
"items": [
{
"type": "Container",
"id": 2,
"label": "left",
"items": [
{
"type": "Menu",
"label": "settings-menu",
"id": "5"
},
{
"type": "Menu",
"label": "main-menu",
"id": "7"
}
]
},
{
"type": "Container",
"id": 4,
"label": "right",
"items": [
{
"type": "Post",
"label": "contact",
"id": "25"
}
]
}
]
},
{
"type": "Postlist",
"label": "nieuwsberichten",
"id": "17"
},
{
"type": "HTML",
"label": "over deze site",
"id": "18"
},
{
"type": "Other",
"label": "twitter feed",
"id": "19"
}
]
}
From the server I get a new object:
var newItem = {
"type": "Post",
"label": "contact",
"id": "25"
}
How can I update the object inside $scope.page the right way? I've tried the following:
$scope.findAndReplace(newItem,$scope.page.items);
$scope.findAndReplace = function(newItem, items) {
for (var i = 0; i < items.length; i++) {
if (items[i].id == newItem.id) {
items[i] = newItem;
} else if (items[i].items) {
$scope.findAndReplace(newItem, items[i].items);
}
}
}
and:
var oldItem = $scope.findById(item.id, $scope.page.items);
oldItem = newItem;
$scope.findById = function(id, items) {
var match = null;
angular.forEach(items, function(i){
if (match == null) {
if (i.id == id) {
match = i;
} else if (i.items) {
match = $scope.findById(id, i.items)
}
}
})
return match;
}
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
Anyone an idea to handle this?
Your example looks fine, can't understand why they are not working.
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
You can keep object reference by using angular.copy(newItem, oldItem)
Hi I have created a fiddle for you.
click for fiddle
for(var indx=0; indx < $scope.page.items.length; indx++) {
var tmpObj = $scope.page.items[indx];
if(tmpObj.hasOwnProperty('items')) {
// check inside
for(var indx1=0; indx1<tmpObj.items.length; indx1++ ) {
var innerObj = tmpObj.items[indx1];
// check for next level
if(innerObj.hasOwnProperty('items')) {
for(var counter=0; counter< innerObj.items.length; counter++) {
var thirdTmp = innerObj.items[counter];
console.log('3rd level inner object', thirdTmp);
if(thirdTmp.id === newItem.id) {
innerObj.items[counter] = newItem;
tmpObj.items[indx1] = innerObj;
$scope.page.items[indx] = tmpObj;
}
}
}
}
} else if(tmpObj.id === newItem.id) {
$scope.page.items[indx] = newItem;
}
};
Related
I have a function to generate an object which I'm transforming to a JSON later on:
function createSearchCriteria(payload) {
var output = [];
if (payload['searchCriteria'] != null) {
for (var i = 0; i < payload['searchCriteria'].length; i++) {
var content = payload['searchCriteria'][i];
output[i] = {};
if (content['grouping'] != null) {
output[i]['groupOperator'] = content['grouping'];
output[i]['searchCriteria'] = [];
output[i]['searchCriteria'].push(createSearchCriteria(content))
} else {
output[i]['name'] = content['name'];
output[i]['type'] = content['type'];
}
}
}
return output
}
The input payload for this method is also a JSON value parsed
payload = JSON.parse(request);
The input structure is almost the same as the output, the only difference is the "grouping" attribute, which in the output is called "groupOperator".
I have implemented my function recursive because we can have different levels of search criteria.
Even though the searchCriteria in the input has only one [] each.
Why does each searchCriteria in the result comes with 2 pairs of squared brackets?
{
"searchCriteria": [
{
"groupOperator": "AND",
"searchCriteria": [
[
{
"groupOperator": "OR",
"searchCriteria": [
[
{
"name": "FirstName",
"type": "string"
},
{
"name": "LastName",
"type": "string"
},
{
"name": "MiddleName",
"type": "string"
},
{
"name": "Document",
"type": "string"
},
{
"name": "DOB",
"type": "date"
},
{
"name": "CdrId",
"type": "string"
}
]
]
},
{
"groupOperator": "AND",
"searchCriteria": [
[
{
"name": "Active",
"type": "bool"
},
{
"name": "Id",
"type": "int"
},
{
"name": "CountryId",
"type": "int"
}
]
]
}
]
]
}
],
"groupOperator": "AND"
}
Thanks in advance for your help.
try
output[i]['searchCriteria'] = createSearchCriteria(content)
instead of
output[i]['searchCriteria'] = [];
output[i]['searchCriteria'].push(createSearchCriteria(content))
Lets say i have 2 Json responses from a server, one of which is 30 seconds older that the new one. How would i be able to check if an object is still inside the response and after testing if it is still there update an object in another json file to add +1 to the number of that object.
(an example because i can´t explain)
JSON coming in
"names and id´s in json changed"
{
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [
{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
}
After cutting out wanted values it looks like this :
[
'07bda75d-d8d2-4108-94a7-ba2c09127nsj',
'8d8aac43-112b-402b-8771-67b49183lazf',
'67d8a66b-ce37-439f-9020-e6de827dn2o9'
]
What i want to do
Now upon a new response coming in i want to update another json file which should idealy look something like this...
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
...and add 1 to the number behind a the certain playerid.
Something like this should work.
let samplePayload = {
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
};
let previousResponseIds = [];
let trackingObj = {};
function responseMiddleware(payload) {
let responseIds = payload.players.sample.map(v => v.id);
let matches = previousResponseIds.filter(v => responseIds.find(x => x === v));
for (let i = 0; i < matches.length; i++) {
if (trackingObj.hasOwnProperty(matches[i])) trackingObj[matches[i]] += 1;
else trackingObj[matches[i]] = 0;
}
previousResponseIds = responseIds;
}
/*UI below*/
let pre = document.getElementsByTagName('pre')[0];
(function updateUI() {
pre.innerText = JSON.stringify(trackingObj, null, 1);
setTimeout(updateUI, 200);
})();
document.getElementById("AddResponse").addEventListener("click", function() {
responseMiddleware(samplePayload);
});
<strong>trackingObj:</strong>
<pre></pre>
<button id="AddResponse">Simulate Response</button>
Let's start with
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
let mainObj = JSON.parse(response1);
let players = JSON.parse(response2);
for (let entry of mainObj.players.sample) {
if (players.players.indexOf(entry.id) > -1) {
players.players[entry.id]++;
}
}
I don't have a chance to test it right this moment, give it a shot, and it should put you on the right track.
I have an array of objects with the following format
var arr = [
{
"productId": "123456",
"productName": "Test Product 1",
"description": [
"This is delicious",
"Suitable for vegetarian"
],
"attributes": {
"internalId": "091283"
"category": "Dairy"
},
"order": 1
}
];
And I am trying to map into something like below
[
[{
{
"name": "productId",
"value": "123456"
},
{
"name": "productName",
"value": "Test Product 1"
},
{
"name": "description",
"value": ["This is delicious", "Suitable for vegetarian"]
},
{
"name": "attributes",
"value": {
{
"name": "internalId",
"value": "091283"
},
{
"name": "category",
"value": "Dairy"
}
}
},
{
"name": "order",
"value": 1
}
}]
]
I tried mapping simple properties before going further and now stuck at getting only the last property of each object in the loop.
Suppose I don't know what are the format of incoming data and how can I normalize the JSON object to the format I want?
normalizeJson = (array) => {
for(i = 0; i < array.length; i++){
normalizedJson[i] = {};
Object.keys(array[i]).forEach(key => {
if (array[i][key] && typeof array[i][key] === "object") {
// normalizeJson(obj[key]);
// console.log(key + ' is object');
return;
} else {
o = {};
o["name"] = key;
o["value"] = array[i][key];
normalizedJson[i] = o;
// normalizedJson[i]["name"] = key;
// normalizedJson[i].value = array[i][key];
// console.log(key);
return;
}
});
}
console.log(normalizedJson);
};
Or is there any library I can use in order to achieve this?
Try this
var obj = [
{
productId: "123456",
productName: "Test Product 1",
description: ["This is delicious", "Suitable for vegetarian"],
attributes: {
internalId: "091283",
category: "Dairy",
},
order: 1,
},
];
function normalizeObject(obj) {
var result = [];
if (Array.isArray(obj)) {
for (let i of obj) {
result.push(normalizeObject(i));
}
} else if (typeof obj == "object") {
for (let i of Object.keys(obj)) {
result.push({ name: i, value: normalizeObject(obj[i]) });
}
} else {
return obj;
}
return result;
}
console.log(JSON.stringify(normalizeObject(obj), null, 2));
This looping method called recursion. Which is loop by calling function itself.
I need to transform below Json array to another array as mentioned below using angularjs/ javascript.
Input Array = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}]
Output Array: [{"Name":"123", "Type1":"24", "Type2":"25"}, {"Name":"124", "Type1":"26", "Type2":"27"}
I would work it out with reduce function I've added some comments for you inside as well:
let inputArray = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
// and do reduce function on it
inputArray.reduce((prevVal, currVal, index) => {
// first check if there's Name in already
if (prevVal.find(x => x.Name === currVal.Name)) {
// if there's a Name same as current element use new type as a key and add Total
prevVal.find(x => x.Name === currVal.Name)[currVal.Type] = currVal.Total;
} else {
// in case there's no Name then just create object with it
prevVal.push({
Name: currVal.Name,
[currVal.Type]: currVal.Total
});
}
return prevVal;
}, []);
Here's fiddle:
https://jsfiddle.net/pegla/s9hwbth4/
All you have to do is, get the unique objects from the original list based on Name.
var obj = [{
"Name": "123",
"Type": "Type1",
"Total": "24"
},
{
"Name": "123",
"Type": "Type2",
"Total": "25"
},
{
"Name": "124",
"Type": "Type1",
"Total": "26"
},
{
"Name": "124",
"Type": "Type2",
"Total": "27"
}
];
var getIndex = function(list, property, object) {
for (var i = 0; i < list.length; i++) {
if (list[i][property] == object[property]) {
return i;
}
}
return -1;
}
var result = [];
for (var i = 0; i < obj.length; i++) {
/* Call getIndex to return the index of element in the result and add the type name property */
var index = getIndex(result, 'Name', obj[i]);
if (index != -1) {
result[index][obj[i].Type] = obj[i].Total;
} else {
var newObj = {};
newObj.Name = obj[i].Name;
newObj[obj[i].Type] = obj[i].Total;
result.push(newObj);
}
}
console.log(result);
You don't need angularjs to do that. You can do that using simple javascript for block. Please see attached code. Best,
let input = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
let output = [];
for(let i=0; i<input.length-1;i++){
output.push({
"Name":input[i].Name,
"Type1":input[i].Total,
"Type2":input[i+1].Total,
});
i++;
}
console.log(output);
I have a simple Json and I need to filter the objects based on a name, In this example I have two movie titles "Paddington" and "Interstaller" and lets say I only want to filter out by name "Paddington" and set the $scope only to the first item "Paddington" item
{
"feed": {
"author": {
"name": {
"label": "iTunes Store"
},
"uri": {
"label": "http://www.apple.com/itunes/"
}
},
"entry": [
{
"im:name": {
"label": "Paddington"
},
"im:image": [
{
"label": "url1",
"attributes": {
"height": "60"
}
},
{
"label": "url2",
"attributes": {
"height": "60"
}
},
{
"label": "url3",
"attributes": {
"height": "170"
}
}
]
},
{
"im:name": {
"label": "Interstellar"
},"im:image": [
{
"label": "url4",
"attributes": {
"height": "60"
}
},
{
"label": "url5",
"attributes": {
"height": "60"
}
},
{
"label": "url6",
"attributes": {
"height": "170"
}
}
]
}
],
"updated": {
"label": "2015-04-18T11:29:36-07:00"
},
"rights": {
"label": "Copyright 2008 Apple Inc."
},
"title": {
"label": "iTunes Store: Top Movies"
}
}
My code
app.controller('movieController', function ($scope, $routeParams, movieService) {
$scope.filterData = function init(){
$scope.movies = movieService.get({id: 4403});// returns the json
var filtered = $filter('filter')($scope.movies.entry, function(value,index){
return value["im:name"].label.indexOf("The Sound")!=-1;
});
$scope.firstItem = filtered[0];
};
alert($scope.firstItem);
});
app.factory('movieService',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {id: '#id'});
});
The $filter service will let you fetch a filter function, there is a filter function called 'filter' that is built in. Documentation here:
https://docs.angularjs.org/api/ng/filter/filter
app.controller('movieController', function ($scope, $filter, $routeParams, movieService) {
alert($routeParams.movieID);
$scope.movies = movieService.get({id: 4403});// returns the json
$scope.movies.$promise.then(function(resp){
var filterFunc = $filter('filter');
var filtered = filterFunc($scope.movies.feed.entry, function(value,index){
return value["im:name"].label.indexOf($routeParams.movieID)!=-1;
});
$scope.firstItem = filtered[0]; // could put this in place of movies but it's confusing since you're re-using that name for the initial resource and this filtered item
});
function test() {
alert(movieService.get({id: 4403}).entry.summary.label);
};
$scope.movies.name = {}; // need to return Paddington
$scope.movies.url = {}; // need to return url3
});
app.factory('movieService',function ($resource) {
return $resource('https://itunes.apple.com/us/rss/topmovies/limit=50/genre=:id/json', {id: '#id'});
});
There isn't an AngularJS-specific solution to this problem, it's a generic JavaScript issue. You want to loop through each object in the JSON dictionary and then check the title.
Something like this:
data = {
'feed': {
'entry': [
{'im:name': 'Paddington'},
{'im:name': 'Interstellar'},
]
}
}
$scope.movies.name = null;
for (var i = 0; i < data.feed.entry.length; i += 1) {
var movie = data.feed.entry.entry[i];
if (movie['im:name'].indexOf('Paddington') !== -1) {
$scope.movies.name = movie.title;
break;
}
}
You can also use the angular.forEach function.