Can't loop through JSON Object Javascript - javascript

I'm trying to loop through a JSON object using javascript. The reason that it is an object and not an array is because the same data is accessed using XAMARIN and C#'s NewtonJSON works better with just JSON Objects instead a mix of objects and arrays.
Below is the JSON object that I am trying to work with, I've cut bits out so you can see the main part of the object that I'm having issues with.
CODE: NULL
VALUE:{
USER24:{id: "24", business: "25", username: "test1", firstName: "test1", lastName: "test1", level: "0",…}
USER25:{id: "25", business: "25", username: "test2", firstName: "test2", lastName: "test2", level: "0",…}
USER26:{id: "26", business: "25", username: "test3", firstName: "test3", lastName: "test3", level: "0",…}
USER27:{id: "27", business: "25", username: "test4", firstName: "test4", lastName: "test4",…}
USER28:{id: "28", business: "25", username: "test5", firstName: "test5", lastName: "test5",…}
USER29:{id: "29", business: "25", username: "test6", firstName: "test6", lastName: "test6", level: "0",…}
USER30:{id: "30", business: "25", username: "test7", firstName: "test7", lastName: "test7", level: "0",…}
}
EXTRA: NULL
The issue I'm having is when I loop through data.VALUE I get the keys and values of USER24 instead of the keys and values of data.VALUE. When I try and loop through just data I get the keys CODE, VALUE, EXTRA like I would expect.
No matter what I place in the loop I won't get the keys and values USER24, USER25, USER26, ... which is what I want. Below I have snippet of the Javascript loop I'm using:
for(var key in data.VALUE){
if(data.VALUE.hasOwnProperty(key)){
console.log('key:'+key+', val:'+data.VALUE[key]);
}
}
All I get back from this is:
key:id, val:24
key:business, val:25
key:username, val:test1
key:firstName, val:test1
key:lastName, val:test1
key:level, val:0
key:email, val:test1#test.co.uk
key:phone, val:null
key:isAdmin, val:true
Which is completely wrong!
I'm not sure what else I am to do for this, I've tried using the $.each from JQuery, I've not used the new let[key, value] as it's far too new at the moment to rely on.
If you need anymore information or code snippets feel free to ask! Thanks in advanced for any help!
Here is a picture of the JSON in the preview tab in chrome (minus some sensitive data):

You can done it by $.each from JQuery like this
$.each(data.VALUE, function (i, key) {
$.each(key, function (j,k) {
console.log('key:'+j+', val:'+k);
});
});
If you want to access it from javascript You are get each key in data.VALUE.USER24 object.
for (var key in data.VALUE.USER24) {
if(data.VALUE.USER24.hasOwnProperty(key)){
console.log('key:' + key + ', val:' + data.VALUE.USER24[key]);
}
}

Related

How to change the name of the property in Vuejs Computed property

Building a VUEJS project - I have computed property being returned from the store. An array of objects.
I want to rename the property name coming from the store (which, behind the scenes is fetching from the API)
For example: What I am getting the response from store/API
{
"f1": "John",
"f2": "Doe",
"f3": "School",
},
{
"f1": "Michael",
"f2": "John",
"f3": "College",
}
]
What I want it to be in the data
[
{
"Nom": "John",
"Prenom": "Doe"
},
{
"Nom": "Michael",
"Prenom": "John"
}
]
I want the computed property to be formatted the way I want it to be.
Also, to remove any unwanted properties coming from the response.
Use Array.map:
computed: {
formatted() {
return json.map(item => ({
Nom: item.f1,
Prenom: item.f2
}));
}
}

using variable name instead of it's value with JavaScript and use it to change an "Object" key identifier

My question is how to change or use the variable name instead of value;
I want to use this snippet:
jsonData.forEach((data)=>{
data.newName= data.api_name;
delete data.api_name;
})
to change the incoming JSON data's key identifier and get that "oldName" from a variable like this
var api_name = "fName";
So for example if this data comes from JSON:
[{
"fName": "John",
"lname": "Smith"
} {
"fName": "Jane",
"lname": "hardy"
}]
and want to have this:
[{
"person_name": "John",
"lname": "Smith"
} {
"person_name": "Jane",
"lname": "hardy"
}]
but if I do it like the snippet I will get error because the JSON doesn't have api_name as it's key identifier.
I hope that I explained enough.
appreciate any help
Use data[api_name] instead of data.api_name . Read more about property accessors.
let jsonData = [{
"fName": "John",
"lname": "Smith"
},{
"fName": "Jane",
"lname": "hardy"
}];
let api_name = "fName";
jsonData.forEach((data)=>{
data.newName= data[api_name];
delete data[api_name];
})
console.log(jsonData);
Try with data[newName]= data[api_name];
eg
newName= 'fName';
api_name='apiName'

Ng-repeat through different objects

I´m trying do ng-repeat with two different objects. In this case I want to return "Name:Leanne Graham, Name: Asier". The JSON file has this.
users: {
0: {
email: "Sincere#april.biz",
id: 1,
name: "Leanne Graham",
phone: "1-770-736-8031 x56442",
username: "Bret",
website: "hildegard.org"
},
1: {
name: "Asier"
}
};
The element who has two objects is $scope.user and I try this
<div ng-repeat="(key, value) in user">{{name}}</div>
Nothing happens, and no errors in console.log.
Provided your data is actually in a valid format, repeating over the collection seems simple enough...
// note: this is just an example to put your data in scope
angular.module('so', []).run(function($rootScope) {
$rootScope.user = {
0: {
email: "Sincere#april.biz",
id: 1,
name: "Leanne Graham",
phone: "1-770-736-8031 x56442",
username: "Bret",
website: "hildegard.org"
},
1: {
name: "Asier"
}
};
});
<div ng-app="so">
<div ng-repeat="usr in user">{{usr.name}}</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

Reorder a JSON collection

I have a JSON array fetch from my server which looks like :
[ {name: "Web Design", id: "27", month_n: "1", data: "68.00"},
{name: "Web Design", id: "27", month_n: "2", data: "56.00"} ,
{name: "Homework", id: "4", month_n: "2", data: "15.00"} ,
{name: "Gaming", id: "12", month_n: "2", data: "5.00"} ]
On the client side, I want to reorder this to have something similar to :
[{name: "Web Design", data:[68.00,56.00]}, {name:"Homework", data:[0,15]} and so on...
Where the "data" value is grouped by the "id" number and the month number (by default 0 if there's no month that match).
What's the best way ? I tried it the pure JavaScript way but I'm getting a hard time ! I have also heard It is easier with underscore JS. But don't know where to start.
Will someone please enlighten me ?
This can be done by two operations:
Groupby [name] field, then
Pluck [data] fields
There are pure JS array prototype extensions libraries to achieve this and many other operations with couple of lines. You may take a look at underscore.js. I have also written a simple JS library jsList. It comes with many unit-tests to use as example.
You only need to write these lines:
var arr = [ {name: "Web Design", id: "27", month_n: "1", data: "68.00"},
{name: "Web Design", id: "27", month_n: "2", data: "56.00"} ,
{name: "Homework", id: "4", month_n: "2", data: "15.00"} ,
{name: "Gaming", id: "12", month_n: "2", data: "5.00"} ];
var temp = arr.groupBy(function(item){ return item.name });
var result = [];
for(var key in temp){
result.push({name: key, data: temp[key].pluck('data')});
}
You may use Object.keys to avoid the for loop, but it only comes with Javascript 1.8.5 or later.
Thanks.
One way to do this in vanilla JavaScript, is to use a helper object as in the following code.
In a first step, we identify all distinct name values and group all data field by them.
In the second step, the helper object is converted back to an array.
var arr = [ {name: "Web Design", id: "27", month_n: "1", data: "68.00"},
{name: "Web Design", id: "27", month_n: "2", data: "56.00"} ,
{name: "Homework", id: "4", month_n: "2", data: "15.00"} ,
{name: "Gaming", id: "12", month_n: "2", data: "5.00"} ];
// use a helper object to identify all distinct "names"
var helper = {};
for( var i=arr.length; i--; ) {
// init an array, if it is not there
helper[ arr[i]['name'] ] = helper[ arr[i]['name'] ] || [];
// add the newest element
helper[ arr[i]['name'] ].push( helper[ arr[i]['data'] ] );
}
// convert back to an array
var newArr = [];
for( var key in helper ) {
if( helper.hasOwnProperty( key ) ) {
newArr.push( { 'name': key, 'data': helper[key] } );
}
}

How to reference data in array of hash in javascript: Windows 8 Metro

I've got some data stored this way:
var protossUnitsArray =
[
{ name: "Zealot", health:"100", shield:"50", armor:"1", picture: "/images/protoss/zealotPortrait.png" },
{ name: "Stalker", health: "80", shield: "80", armor: "1", picture: "/images/protoss/stalkerPortrait.png" },
{ name: "Sentry", health: "40", shield: "40", armor: "1", picture: "/images/protoss/sentryPortrait.png" },
{ name: "High Templar", health: "40", shield: "40", armor: "0", picture: "/images/protoss/hightemplarPortrait.png" },
{ name: "Dark Templar", health: "40", shield: "80", armor: "1", picture: "/images/protoss/darktemplarPortrait.png" },
{ name: "Immortal", health: "200", shield: "100", armor: "1", picture: "/images/protoss/immortalPortrait.png" }
];
var protossUnitsList = new WinJS.Binding.List(protossUnitsArray);
var publicMembers =
{
itemList: protossUnitsList
};
WinJS.Namespace.define("ProtossUnitsData", publicMembers);
As you can see, the array has been made publicly available.
How do I actually reference data from this array from another javascript file?
Let's say I want to know what a Stalker's health is (which is 80). Let's assume I know Stalkers are always going to be the second item in the array, shouldn't it be something like
ProtossUnitsData.itemList[1]['health'] ?
But that's not quite right..
If you want to access 2nd item from the array protossUnitsArray, shouldn't it be:
protossUnitsArray[1].health
I don't know about Windows 8 and the UI formerly known as Metro, but in JavaScript shouldn't it just be:
ProtossUnitsData.itemList[1].health
Edit
Looking at the documentation, it seems that WinJS.Binding.List exposes methods for working with the data in the List. See here and here for more info, but it looks like you want to use:
var item = ProtossUnitsData.getItem(1),
data = item.health;
That might work...
Figured it out! It's actually:
ProtossUnitsData.itemList.getAt(1).health;

Categories

Resources