how to access specific data in json in javascript - javascript

I'm trying to access specific data from json array. and i'm using dynamic dropdown.
So in my case i want get all names from the json and plot it on option.
here is the Json we're accessing..
[
{
"id": 1,
"name": "john"
"age": 23,
"city": "New York"
},
{
"id": 2,
"name": "Donald"
"age": 34,
"city": "London"
},
{
"id": 3,
"name": "k'nan"
"age": 27,
"city": "Paris"
},
{
"id": 1,
"name": "jose"
"age": 29,
"city": "lesbon"
},
]
script
$.each(data, function(key,vlaue ){
$('select[name="bus_number"]').append('<option value="'+ key +'">'+ value +'</option>');
});
and again i want to access only all names and plot it on options.
i did this and it's not working and may be you guys will tell me a better way.

Brb to explain soon.
Jquery:
var data = [
{
"id": 1,
"name": "john",
"age": 23,
"city": "New York"
},
{
"id": 2,
"name": "Donald",
"age": 34,
"city": "London"
},
{
"id": 3,
"name": "k'nan",
"age": 27,
"city": "Paris"
},
{
"id": 1,
"name": "jose",
"age": 29,
"city": "lesbon"
},
];
$.each( data, function( index, object ) {
$('select[name="bus_number"]').append('<option value="'+ object['id'] +'">'+ object['name'] +'</option>');
});

I'm assuming that you are trying to create a dropdown where the options' labels are the names in the data and the options' values are the corresponding ids.
data.forEach(({id, name}) => {
$('select[name="bus_number"]').append(`<option value="${id}">${name}</option>`);
});
Notice that I use JavaSctipt's native forEach instead of jQuery's (no need for that anymore), and I'm also using Object Desctructuring and String Literals which make your code easier to read.
Here's a fiddle.

Related

How to remove a child object from a JSON object using javascript

I'm trying to search through a JSON object to find the pet-rock that I want to delete. Here is a simple JSON that I'm working on:
myData.json:
{
"data": [
{
"name": "John",
"age": "25",
"pet-rocks": [
{
"name": "Travis",
"age": "9"
},
{
"name": "Steven",
"age": "5"
},
{
"name": "Oliver",
"age": "7"
}
]
},
{
"name": "Jane",
"age": "25",
"pet-rocks": [
{
"name": "Jesse",
"age": "4"
},
{
"name": "Carol",
"age": "8"
},
{
"name": "Jake",
"age": "7"
}
]
}
]
}
I would like to do a search for "Steven" and remove that pet-rock from the list. Here are the things I've tried:
MyJSFile.js:
const myDataObject = require('./myData.json');
for (let key in myDataObject) {
let value = myDataObject[key];
if (value === "Steven")
{
delete myDataObject[key];
}
//To see if I get the data I want
console.log(key, value);
}
However, my output is strange and I'm not sure how to get to that child node of petrock. It appears that the petrocks are in object form, and I'm not sure how to get to them. here is the ouput of my console below. I assume it didn't get delete as there are still 3 petrock objects in the data.
data [
{
name: 'Robert',
age: '25',
'pet-rocks': [ [Object], [Object], [Object] ]
},
{
name: 'Robert',
age: '25',
'pet-rocks': [ [Object], [Object], [Object] ]
}
]
Any help or suggestions would be greatly appreciated! Thanks!
The pet rock named Steven is not a direct child of myDataObject, so you can't delete it like that. You can loop through the "data" array, rebuilding the "pet-rocks" array for each element. A simple filter to remove any pet rocks named Steven should work.
const myDataObject = {
"data": [
{
"name": "John",
"age": "25",
"pet-rocks": [
{
"name": "Travis",
"age": "9"
},
{
"name": "Steven",
"age": "5"
},
{
"name": "Oliver",
"age": "7"
}
]
},
{
"name": "Jane",
"age": "25",
"pet-rocks": [
{
"name": "Jesse",
"age": "4"
},
{
"name": "Carol",
"age": "8"
},
{
"name": "Jake",
"age": "7"
}
]
}
]
};
myDataObject.data.forEach(d => {
d["pet-rocks"] = d["pet-rocks"].filter(rock => rock.name !== "Steven");
});
console.log(myDataObject);

How to filter an array of objects in Kendo Grid (AngularJs)?

I have a Document object like this:
{"id": 1, "annotation": "some text", "signers": [{ "id": 32, "name": "Bob", "address": {"country": "USA"}},
{ "id": 44, "name": "Bill", "address": {"country": "Canada"}}]}
Documents are displayed in a Kendo grid, and one of the columns is for signers. How is it possible to filter signers by name (and also by country, but that is less relevant)? How to filter an array of objects?
I've been trying to figure out how to write a custom filter function and do all the filtering on client side, but I haven't been able to figure this out.
You can create a Set of the names or countries to search for and call Set#has in the callback for Array#filter.
let doc = {"id": 1, "annotation": "some text", "signers": [{ "id": 32, "name": "Bob", "address": {"country": "USA"}},
{ "id": 44, "name": "Bill", "address": {"country": "Canada"}}]};
const names = new Set(["Bob", "Joe"]);
doc.signers = doc.signers.filter(({name})=>names.has(name));
console.log(doc);

Find object by property in JSON array

I have problem with get string in JSON data. Format as below:
[
{
"name": "Alice",
"age": "20"
},
{
"id": "David",
"last": "25"
},
{
"id": "John",
"last": "30"
}
]
Sometime it changes position together, John from 3rd place go to 2nd place:
[
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
]
If i use data[3].age to get John's age, and data change position, I will get David's age.
Is there any method I can use to find the object with name David and get the age value?
You can use array.find() method as,
var myArray = [
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
];
//Here you are passing the parameter name and getting the age
//Find will get you the first matching object
var result = myArray.find(t=>t.name ==='John').age;
console.log(result);
It's better to use array.filter() (better browser support)
myArray.filter(function(el){return el.name == "John"})[0].age

How to remove or hide a key-value pair of an array in AngularJS

I have a collection of objects in an array like this:
[
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
},...
]
In my view I only want to display Name, Age, City and Country. Well, my question is how can I remove GROUP_ID and ACTIVE in every object of my collection? I was looking for a solution and found .slice() but I don't know exactly whether is it the right one and how to use this javascript function for each object in an array.
EDIT:
For more clarification. My view is defined like below:
<md-list-item ng-repeat="cItems in ::contentItems track by $index">
<span ng-repeat="(key, value) in cItems track by $index" flex="auto">
{{ ::value }}
</span>
<md-divider></md-divider>
</md-list-item>
You can use the following lines:
contentItems.forEach(function (entry) {
delete entry['GROUP_ID'];
delete entry['ACTIVE'];
});
As mentioned in comments there is no need to delete the keys. You can simple avoid displaying them.
Still if deleting is objective then use delete method
a.forEach(function(item){
delete(item['GROUP_ID']);
delete(item['ACTIVE'])
});
DEMO
Assuming your array is a variable named array:
for ( var i=0,l=array.length; i<l; i++ ) {
delete array[i]['GROUP_ID'];
delete array[i]['ACTIVE'];
}
if you're using ES6 you could also do:
for ( let item of array ) {
delete item['GROUP_ID'];
delete item['ACTIVE'];
}
You can simply remove properties of an object by using delete. I've added an array of properties to delete but you could delete them directly.
var data = [
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
}
];
var propertiesRemove = ['GROUP_ID', 'ACTIVE']
data.forEach(function(item){
propertiesRemove.forEach(function(prop){
delete item[prop];
});
});
console.log(data);
If you don't want to change your data and it's just a display issue you could render only the properties you want.
<md-list-item ng-repeat="cItems in ::contentItems track by $index">
<span flex="auto">{{cItems.NAME}}</span>
<span flex="auto">{{cItems.AGE}}</span>
<span flex="auto">{{cItems.CITY}}</span>
<span flex="auto">{{cItems.COUNTRY}}</span>
<md-divider></md-divider>
</md-list-item>
Actually to display required information in angular we don't need to remove other elements from array in template we can go with limited information.
ANGULAR CODE
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
}
]
});
Angular Template
<body ng-app="myApp" ng-controller="myCtrl">
<ul ng-repeat="record in records">
<li>{{record.NAME}}</li>
<li>{{record.AGE}}</li>
<li>{{record.COUNTRY}}</li>
</ul>
But as you are asking following procedure will answer your question.
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$data = [
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA",
"GROUP_ID": 1,
"ACTIVE": 1
},
{
"NAME": "Peter Parker",
"AGE": 44,
"CITY": "Los Angeles",
"COUNTRY": "USA",
"GROUP_ID": 2,
"ACTIVE": 1
}
];
$scope.records = $data.map(function(item){
delete(item['GROUP_ID']);
delete(item['ACTIVE']);
return item;
});
});

Using ember-data with custom serializer

I have you could say a non standard json api. I'm trying to use ember-data with it so from my reading around I need to create a serializer. I tried to find article online explaining how to do this but haven't found anything useful. I tried looking through the ember guides but also found nothing. Here is an example of my api:
collection of data:
{
"data": [
{
"id": 14,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 10,
"address": "10000 sw 16th ct",
"city": "Hollywood",
"state": "Alabama"
}
},
"employees": {
"data": [
{
"id": 17,
"first_name": "Peter",
"last_name": "Griffin",
"email": "company-name#Griffin.co"
},
{
"id": 18,
"first_name": "Robert",
"last_name": "Gornitz",
"email": null
}
]
}
},
{
"id": 8,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 8,
"address": "1000 n university dr",
"city": "Fort Lauderdale",
"state": "West Virginia"
}
},
"employees": {
"data": [
{
"id": 15,
"first_name": "Peter",
"last_name": "Griffin"
},
{
"id": 16,
"first_name": "Peter",
"last_name": "Griffin"
}
]
}
}
]
}
Here is an item with its relationships:
{
"data": {
"id": 1,
"name": "company name",
"slug": "company-name",
"detail": {
"data": {
"id": 1,
"address": "1515 n university dr",
"city": "Miami",
"state": "Mississippi"
}
},
"employees": {
"data": [
{
"id": 1,
"first_name": "Peter",
"last_name": "Griffin",
"email": "peter#email.com"
},
{
"id": 2,
"first_name": "Peter",
"last_name": "Griffin",
"email": "peter#email.com"
}
]
}
}
}
Are there any good resources showing me how to do this? Or should I just not use ember-data?
Just some tips from my side using Ember Data. I believe that you either have to be able the adapt api or write a deserializer:
1. Root Key "data"
Ember expects the root key to be the name of the model (e.g. "company"). You can handle that easily by creating an application serializer and overwriting the extractArray and extractSingle method by grabbing the payload from the 'data' key instead of the model "typeKey".
2. Embedded Records
You can use the EmbeddedRecordsMixin. But for that you will have to skip the root key "data" in the embedded records and directly include them (e.g. "employees": [ { id: "2", ... }, ... ])
I'd have a look at the EmbeddedRecordsMixin for that:
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize
Hope that helps a little.

Categories

Resources