add a element to json array with Key/value using angular js - angularjs

I have a json array object like below
$scope.Json = [{
Id:"5464",
Class:"9",
Rank:"4"
}]
I want to add a item "Name":"Vicky" to the Json. So that my result should be as below.
$scope.Json = [{
Id:"5464",
Class:"9",
Rank:"4",
Name:"Vicky"
}]
I am new to angular, can anyone help on this?

Use Array map() method.
DEMO
var json = [{ Id:"5464", Class:"9", Rank:"4" }];
json.map(function(item) {
item.Name = 'Vicky';
});
console.log(json);

First of all, the object $scope.Json is not a JSON but a string. To get a JSON, you need to parse the string like the following:
$scope.Json = JSON.parse(<string>) ;
Second, your input is a peculiar JSON as it is an array with one element (in its turn having 3 elements. I guess you wanted this:
$scope.Json = JSON.parse({ Id:"5464", Class:"9", Rank:"4" }) ;
Once you have this, you can add the element you want as:
$scope.Json.Name = "Vicky" ;

Related

GetJson with Object.values with commas within text. How to get rid of these commas?

I would like to get a specific value from a JSON with GetJson but it is inserting commas within the value/text. Here is the structure of my JSON:
{"api":
{"results":10,"fixtures":
[{"fixture_id":293298,
"league_id":1251,
"league":
{"name":"CONMEBOL Libertadores",
"country":"World",
"logo":.....
I am trying to get the "name" value i.e. "CONMEBOL Libertadores" instead I'm getting "C,O,N,M,E,B,O,L, ,L,i,b,e,r,t,a,d,o,r,e,s".
$(document).ready(function(){
$.getJSON("proxliberta.json", function(data) {
$.each(data.api.fixtures, function() {
});
console.log(Object.values(data.api.fixtures[1].league.name));
document.getElementById('val').innerHTML = Object.values(data.api.fixtures[1].league.name)
});
});
How can I eliminate these commas within my response? Thanks!
Instead of
Object.values(data.api.fixtures[1].league.name)
try changing to,
data.api.fixtures[1].league.name
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

How to filter a multidimentional JSON Object

I have a Json string which contains many json objects, each json has a key, I use JSON.parse to place the string into an object.
I then extract what I need in the following format
json['product1'][0].name
However, I want to get an array of element from each of the json objects based on the value of another elements. Currently I am using:
for each (var row:Object in json) {
if (row[0][filterElement] == filterValue) {
arr.push(row[0][element]);
}
}
Is this a good approach? I ask because it seems that I am going through the entire json object every time.
If I've understood your question correctly, it sounds like you want to use .map and .filter.
So if we have an object such as...
var obj = {
people: [
{name: 'person1'},
{name: 'person2'},
{name: 'person3'},
{name: 'person4'},
]
};
You can then use .map to create a new array of names...
var names = obj.people.map(function(person){
return person.name;
}); // ['person1', 'person2', 'person3', 'person4']
on this array you can then use .filter...
var filter = 'person2';
var filteredNames = obj.people.map(function(person){
return person.name;
}).filter(function(name){
return name == filter; // if true, will push name into a name into our new array
}); // 'person2'
This is obviously a rudimentary example, but the same concepts will apply for the precise properties which apply in your question. Hope this helps.

How to query a JSON object

In my AngularJS web app, How can I query a JSON object ?
For example in the below JSON object how can I find the value of reportTypeLabel where reportTypeId=3
JSON:
[
{
reportTypeId:5,
reportTypeCode:"FINREP",
reportTypeLabel:"Financial Reporting"
},
{
reportTypeId:9000002,
reportTypeCode:"REM HE",
reportTypeLabel:"High Earners"
},
{
reportTypeId:3,
reportTypeCode:"COREP LE",
reportTypeLabel:"Large Exposures - COREP"
}
]
You can require $filter service and do
var elements = $filter('filter')(arrayOfObjects,{reportTypeId: 3});
elements will be an array of all the elements with that 'reportTypeId'
i would recommend reading about angular filters and https://docs.angularjs.org/api/ng/service/$filter
If you're going to use data manipulation extensively, I'd highly recommend using a JS library, like underscore or lodash.
For example, using underscore:
// assuming your object is called data
var result = _.findWhere(data, {
reportTypeId: 3
}).reportTypeLabel;
// result === 'Large Exposures - COREP'
You could do this
<div ng-repeat="report in reports | filter:{reportTypeId:'3'}">
{{report.reportTypeCode}}
</div>
Working Fiddle
You can use regular filter function on array:
var items = [
{reportTypeId:5, reportTypeCode:"FINREP"},
{reportTypeId:9000002, reportTypeCode:"REM HE"}
];
var onlyMatching = items.filter(function(item){ return item.reportTypeId == 3; });
Or an angular filter in html
<div ng-repeat="item in items | filter: {reportTypeId: '3'}">{{item. reportTypeLabel}}</div>
Or an angular filter through $filter service
module.controller('ItemsCtrl', function($filter){
$scope.filtered = $filter('filter')($scope.items,{ reportTypeId: '3' });
});

How to remove the angular scope array values using key name?

I have an angular scope array now i want to remove one item from that array using key name for example i want to remove DataTypeName from that array.
$scope.attributes = [
{DataTypeName: "Text"
objectAttributeDataTypeId: "3654B05F-E09E-49A9-8E5F-0FC623BBE009"
objectAttributeId: "9df52354-67dd-453a-87fd-abb38b448db9"
objectAttributeLabelName: "test"
objectAttributeName: "test"}]
Please anyone help me to remove the array.
seems like you need to remove the objectAttributeDataTypeId from the first element of the array which is a object.
so what you need is,
$scope.attributes[0] // get the first element of the array
$scope.attributes[0].DataTypeName // get the DataTypeName attribute of the object
delete $scope.attributes[0].DataTypeName; // delete the property.
so all you need is,
delete $scope.attributes[0].DataTypeName;
If you want to filter array you can use native Array.prototype.filter method for this:
$scope = {}; // stub $scope for demo
$scope.attributes = [
{
DataTypeName: "Text",
objectAttributeDataTypeId: "3654B05F-E09E-49A9-8E5F-0FC623BBE009",
objectAttributeId: "9df52354-67dd-453a-87fd-abb38b448db9",
objectAttributeLabelName: "test",
objectAttributeName: "test"
},
{
DataTypeName: "Image",
objectAttributeDataTypeId: "3654B05F-E09E-49A9-8E5F-0FC623BBE009",
objectAttributeId: "9df52354-67dd-453a-87fd-abb38b448db9",
objectAttributeLabelName: "test",
objectAttributeName: "test"
}
];
// Filter out only "Text" types
$scope.filtered = $scope.attributes.filter(function(attr) {
return attr.DataTypeName == "Text";
});
document.write('<pre>' + JSON.stringify($scope.filtered, null, 4));

Converting JSON object format using angularjs

I am new to Angularjs.I want to change the format of the JSON object code which I am getting into some new format.Below is the format.
$scope.filters={"filters":
[{"filterId":"106","filtername":"Service Line","filterValue":"ADI"},
{"filterId":"107","filtername":"Service Line","filterValue":"L"},
{"filterId":"108","filtername":"Service Line","filterValue":"M"},
{"filterId":"109","filtername":"Location","filterValue":"N"},
{"filterId":"110","filtername":"Band","filterValue":"O"}
]};
I want this to be changed into below format using angularjs.
$scope.filters=[{"filters":
{"ServiceLine":["ADI","L","M"],
"Location":["N"],
"Band":["0"]}
}] ;
Can anyone guide me here?
I agree with kachhalimbu that you can use underscore.js or lodash.js and use it's map function to transform you json object to another form.
If you still want to transform without using another framework you can do something like this:
var filterObject = { "filters": {} };
angular.forEach($scope.filters.filters, function(filter) {
if(!filterObject.filters[filter.filtername]) {
filterObject.filters[filter.filtername] = [];
}
filterObject.filters[filter.filtername].push(filter.filterValue)
});
filterObject will contains that format you want to use, after that you can do something like this:
$scope.filters = [];
$scope.filters.push(filterObject);

Resources