Sample JSON Data:
{
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]}
With this sample data I can display individual values from the results [] array with object.name and object.phone to look something like:
John Smith 555-555-1111<br />
Mary Jones 555-555-2222<br />
Edward Edwards 555-555-3333<br />
Abby Abberson 555-555-4444
What I am trying to do now is select just the people who's state value is NY and only display their object.name and object.phone:
John Smith 555-555-1111<br />
Edward Edwards 555-555-3333
I tried this lovely little block but all it did was print all the names, which makes sense after I tried it.
if (object.state = "NY") {
div.append(repName);
}
I can't seem to think of a way to only display those that share a the same state.
I'm probably searching for the wrong terms or have to go about this another way... please help!
You are using =(assignment operator),which is wrong.
You have to use ==(comparison operator)
So do like below:-
if (object.state == "NY") {
div.append(repName);
}
Working sample-
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]};
$(obj.results).each(function(k,object){
if (object.state == "NY") {
$('#final_data').append(object.name +" : "+object.phone+"<br/>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="final_data"></div>
My one cent solution:
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]};
obj.results.forEach((value) => {
if (value.state === "NY") {
const li = document.createElement("li");
li.innerHTML = `${value.name} : ${value.phone}`;
document.querySelector("#final_data").appendChild(li);
}
});
<ul id="final_data"></ul>
Like Alive said you used the assignment operator = instead of comparison operator === or ==.
Related
I have a sample object structure like below
Even though there are three types of addresses (address, employeeAddress, shippingAddress), they all represent the same data structure called address. From this object structure, I need to get all the addresses from the above structure.The object structure might be defined in using a JSON Schema format.
Also the addresses need not be always as part of the same hierarchy. For example in the above, shippingAddress and employeeAddress are at different hierarchy.
I tried with object's hasOwnProperty, but did not work the way as expected. Did not get much help from the filter method in lodash also. Is there an elegant way to achieve this?
{
"user": {
"firstName": "John",
"lastName": "Steve",
"address": {
"houseNo": "24",
"city": "CA",
"country": {
"code": "US",
"name": "United States"
}
}
},
"employee": {
"employeeID": "443434",
"employeeName": "Steve",
"employeeAddress": {
"houseNo": "244",
"city": "NJ",
"country": {
"code": "US",
"name": "United States"
}
}
},
"assistant": {
"assitantID": "443434",
"employeeName": "Steve",
"shippingDetails": {
"shippingAddress": {
"houseNo": "2444",
"city": "LA",
"country": {
"code": "US",
"name": "United States"
}
}
}
}
}
You could use recursion for this and create a function that takes input data and schema object. Then on each level another function checks if the current object matches schema structure.
const data = {"user":{"firstName":"John","lastName":"Steve","address":{"houseNo":"24","city":"CA","country":{"code":"US","name":"United States"}}},"employee":{"employeeID":"443434","employeeName":"Steve","employeeAddress":{"houseNo":"244","city":"NJ","country":{"code":"US","name":"United States"}}},"assistant":{"assitantID":"443434","employeeName":"Steve","shippingDetails":{"shippingAddress":{"houseNo":"2444","city":"LA","country":{"code":"US","name":"United States"}}}}}
const schema = {
houseNo: null,
country: null,
city: null
}
function match(o1, o2) {
return Object.keys(o1).every(k => k in o2);
}
function get(data, schema) {
return Object.keys(data).reduce((r, e) => {
if (match(data[e], schema)) r.push(data[e]);
else if (typeof data[e] == 'object') r.push(...get(data[e], schema));
return r;
}, [])
}
const result = get(data, schema);
console.log(result)
Here is a plain JS version of one found here
var user = { "user": { "firstName": "John", "lastName": "Steve", "address": { "houseNo": "24", "city": "CA", "country": { "code": "US", "name": "United States" } } }, "employee": { "employeeID": "443434", "employeeName": "Steve", "employeeAddress": { "houseNo": "244", "city": "NJ", "country": { "code": "US", "name": "United States" } } }, "assistant": { "assitantID": "443434", "employeeName": "Steve", "shippingDetails": { "shippingAddress": { "houseNo": "2444", "city": "LA", "country": { "code": "US", "name": "United States" } } } } }
function findProp(obj, prop) {
var result = {};
function recursivelyFindProp(o, keyToBeFound) {
Object.keys(o).forEach(function (key) {
if (typeof o[key] === 'object') {
if (key.toLowerCase().indexOf(keyToBeFound) !==-1) result[key]=o[key];
recursivelyFindProp(o[key], keyToBeFound);
} else {
if (key.toLowerCase().indexOf(keyToBeFound) !==-1) result[key]=o[key];
}
});
}
recursivelyFindProp(obj, prop);
return result;
}
console.log(
findProp(user, "address")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
I'm trying to omit req.body data, when updating a resource in a collection, with only the fields that are null or '' for that existing resource in the collection.
But this could also be generic, that's why the title is more generic.
Anyways, imagine the following:
We have a user in our database with the following data:
{
"firstName": "John",
"lastName": "Doe",
"address": {
"Address1": "Random street 1",
"City": "",
"Country": null
},
"email": ""
}
The user is trying to update the existing resource with the following data:
{
"firstName": "Mark",
"address": {
"Address1": "Random street 2",
"City": "NY",
"Country": "USA"
},
"email": "john.doe#mail.com"
}
Updated object should like like this:
{
"firstName": "John", // Unchanged because propety value already exists
"lastName": "Doe",
"address": {
"Address1": "Random street 1", // Unchanged because propety value already exists
"City": "NY", // Updated because existing value is empty ("")
"Country": "USA" // Updated because existing value is null
},
"email": "john.doe#mail.com" // Updated because existing value is empty ("")
}
I'm using mongoose, but I would rather implement this on the basic javascript object level
I am not aware of any library but below is the working example using recursion.
var oldObj = {
"firstName": "John",
"lastName": "Doe",
"address": {
"Address1": "Random street 1",
"City": "",
"Country": null
},
"email": ""
}
var newObj = {
"firstName": "Mark",
"address": {
"Address1": "Random street 2",
"City": "NY",
"Country": "USA"
},
"email": "john.doe#mail.com"
}
updateObject(oldObj, newObj);
function updateObject(oldObj, newObj) {
Object.keys(oldObj).forEach( key => {
if (oldObj[key] && typeof oldObj[key] === 'object') {
updateObject(oldObj[key], newObj[key]);
} else {
oldObj[key] = oldObj[key] || newObj[key];
}
});
}
console.log("Modified Obj: ", oldObj);
Hope this may help you.
Can someone please point out where I am making a mistake.
Its a very simple application that is meant to print out the "name" field in and array of Json objects, Which is done via the line :
{{ctrl.contact[0].results[0].name.first}} or
{{ctrl.contact[1].results[0].name.first}}
(which in itself seems very convoluted)
I cannot get it to print out the name of each Json block individually by loop and here is what i have tried :
<div ng-repeat="i in ctrl.contact">
<span>{{ctrl.contact[i].results[0].name.first}}</span>
</div>
Im confident after spending a few hours tweaking and editing that my angular set up (app, controller etc) is fine.
code snippet below :
<html ng-app="ContactAppApp">
<head>
<title>My Contact App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
</head>
<body>
<div>
<div ng-controller="ContactAppController as ctrl">
<h1>{{ctrl.test}}</h1>
<div ng-repeat="i in ctrl.contact">
<span>{{ctrl.contact[0].results[0].name.first}}</span>
</div>
</div>
</div>
</body>
<script>
var app = angular.module("ContactAppApp", [])
app.controller("ContactAppController", ContactAppController);
function ContactAppController() {
this.test = "This text is generated by Angular";
this.contact = [
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "tony",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
},
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "Jack",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
}
]
}
</script>
</html>
Try the following:
<div ng-repeat="i in ctrl.contact">
<span>{{i.results[0].name.first}}</span>
</div>
I would set up your array a little differently. Try something like this:
this.contact = {
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "tony",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
},
{
"gender": "male",
"name": {
"title": "mr",
"first": "Jack",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
}
Then in your ng-repeat, try something like this:
<div ng-repeat="item in contact.results">
<span>{{item.name.first}} {{$index}}</span>
</div>
If you are trying to track the index of the item in array, use $index, not i.
function main(message){
...
phone= JSON.parse(message.phoneNumbers);
... }
My input JSON is
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
The result I receive is omitting the "phoneNumbers" but I do want it.
Your data is correct, when i JSON.parse it, i get everything allright.
But you don't seem to access to your data in the right way. You must first parse the whole JSON, then you have a javascript object, and only then you can acces your property.
in detail:
var obj = JSON.parse(message);
var phone = obj.phoneNumbers;
or in short:
var phone = (JSON.parse(message)).phoneNumbers;
I have a solution of my question, but I don't know whether it exists a better solution.
Following I had implemented:
View:
<md-list>
<md-list-item>
<span ng-repeat="item in ::items track by $index" flex="auto">
{{::item}}
</span>
<md-divider></md-divider>
</md-list-item>
</md-list>
Controller:
CrudSvc.GetAll().$promise.then(
function (res) {
$scope.items = GetKeyForTitle(res);
},
function (err) {
//err code...
}
);
function GetKeyForTitle(data) {
var arrItems = [];
var resData = data[0];
angular.forEach(resData, function (val, key) {
arrItems.push(key);
});
return arrItems;
}
JSON data is simple defined:
[
{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA"
},...
]
For my solution I used data[0] to give me only the first data otherwise I get always the same keys and I need the keys just one time.
Use Object.keys():
var data = [{
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA"
}, {
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA"
}, {
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA"
}, {
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA"
}, {
"NAME": "John Doe",
"AGE": 25,
"CITY": "New York",
"COUNTRY": "USA"
}]
var arrItems = Object.keys(data[0]);
console.log(arrItems);
https://repl.it/E0lI
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
You can use
var allKeys = [];
for(var key in myObject) allKeys.push(k);
console.log("Keys " + allKeys.length + " keys: " + allKeys);
Or if you are using Lodash/underscore they it makes your life even easier.