I am trying to pull the user information by passing some object values as rest parameter. Whenever I try to pass 2 arguments, the code throws an error (undefined). What is it that I am missing?
Here is the Jsfiddle link of what I am trying to do.
let userAddress = [{
"street": "someStreet1",
"house": "1",
"person": "User1"
}, {
"street": "someStreet2",
"house": "2",
"person": "User2"
}, {
"street": "someStreet3",
"house": "3",
"person": "User3"
}];
let userInfo = [];
let addressToCheck = (...newUserHouse) => {
for (let address of userAddress) {
if (newUserHouse == address.house) {
userInfo.push(address.person);
console.log(userInfo);
}
}
}
console.log(addressToCheck(3, 2));
EDIT
Additional info:
I had this problem in which I had a JSON data and I had to pass multiple values and check whether those values were present in the dataset or not and if present, display the whole object.
For example; In the userAddress Array (as shown above) I need to check if 3, 2 (passed as an argument) are present as house number in userAddress. If they are present, then display the whole information about that particular object. As in this case, since 3, 2 are valid house numbers, the expected result should be:
Object { "street": "someStreet2", "house": "2", "person": "User2" }
Object { "street": "someStreet3", "house": "3", "person": "User3" }
The code does not throw an undefined error, it simply logs the value undefined. And that happens because you are calling console.log on the return value of addressToCheck but the function doesn't return a value, so it implicitly returns undefined. See console.log returns an additional undefined.
However, there are more problems with your code. It only accidentally works when you pass a single argument because you are using loose comparison (==).
The value of a rest parameter is always an array. That means you are really doing the following comparisons:
[1, 2] == "1"
[1, 2] == "2"
[1, 2] == "3"
I hope it's obvious why this cannot work. An array with multiple elements cannot be equal to a single "element", so the if condition is never fulfilled.
It works accidentally with a single argument because the string representation of [1] is simply "1". The string representation if [1,2] however is "1,2".
You are not explaining what the desired outcome is but if you want to select all addresses for the provided input, you should be using .filter instead. And you can convert the provided arguments to a set for fast lookup.
Instead of assigning values to an "external" array, simply return the result from the function.
let userAddress = [{
"street": "someStreet1",
"house": "1",
"person": "User1"
}, {
"street": "someStreet2",
"house": "2",
"person": "User2"
}, {
"street": "someStreet3",
"house": "3",
"person": "User3"
}];
let addressToCheck = (...newUserHouse) => {
newUserHouse = new Set(newUserHouse);
return userAddress.filter(address => newUserHouse.has(address.house));
};
console.log(addressToCheck("3", "2"));
A functional way to achieve this using ES6 is to utilize the Array's filter() and includes() methods in a custom function, (namely getUsersMatchingHouseNumbers), as shown in the gist below:
const userData = [{
"street": "someStreet1",
"house": 1,
"person": "User1"
}, {
"street": "someStreet2",
"house": 2,
"person": "User2"
}, {
"street": "someStreet3",
"house": 3,
"person": "User3"
}]
function getUsersMatchingHouseNumbers(userData, ...houseNumbers) {
return userData.filter(({ house }) => houseNumbers.includes(house));
}
console.log(getUsersMatchingHouseNumbers(userData, 1, 3));
Notes
The userData.filter(({ house }) part uses Object destructuring to obtain only the house property/value from each userData object.
The getUsersMatchingHouseNumbers function returns an array of user objects whose house number matches those passed to the function when it is invoked.
In my code, I was missing out the point that rest parameters are an array of parameters and in order to manipulate them, we have to iterate over them too.
let userAddress = [{
"street": "someStreet1",
"house": 1,
"person": "User1"
}, {
"street": "someStreet2",
"house": 2,
"person": "User2"
}, {
"street": "someStreet3",
"house": 3,
"person": "User3"
}]
let addressToCheck = (...houses) => {
for(let house of houses){
for (let user of userAddress) {
if(user.house === house){
console.log(user);
break;
}
}
}
}
console.log(addressToCheck(1, 3));
Related
{
"data": [
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "abx",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800001"
}
},
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "xyz",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800002"
}
},
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "ijk",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800003"
}
}
]
}
Out put json should be like this
[
{
"name": "abx",
"Pin": "800001"
},
{
"name": "xyz",
"Pin": "800002"
},
{
"name": "ijk",
"Pin": "800003"
}
]
From the input json, I want to extract all values using
jpath
Name Path = "data.name"
Pin Path = "data.address.pin"
I need all values, I will create an output json.
If both json and jpath are dynamic then try using the below code, here i have used the same input json and output json in my code block.
$(document).ready(function () {
var outputArr = [];
//Assume that these jpaths are dynamic.
var name = "data.name", pin = "data.address.Pin";
//Assigned input json object to sampleData variable.
$.each(sampleData.data, function (item, value) {
//Replacing 'data.' with empty('') as we are looping through data array.
var nameValue = extractValue(value, name.replace('data.', ''));
var pinValue = extractValue(value, pin.replace('data.', ''));
outputArr.push({ 'name': nameValue, 'Pin': pinValue });
});
//logging into console for testing purpose.
console.log(outputArr);
--to do with outputArr --
//Recursive function that returns the required value from the json
function extractValue(value, jPathKey) {
if (jPathKey.split(".").length > 1) {
//Here use of replace function is must as we need to get the object with the mentioned jPathKey to loop further.
return extractValue(value[jPathKey.replace('.', '$').split('$')[0]], jPathKey.replace('.', '$').split('$')[1])
}
else {
return value[jPathKey];
}
}
});
Note: Here only thing that need to take care is the case of jpath should match with case of input json
I am trying to parse a JSON response that has repeating objects with JsonSlurper to compare to a JDBC query. However, I only want to compare objects where a certain values exist within that object.
If I had a response that looks like this, how would I only parse the objects where the country equals USA or Canada, therefore ignoring anything else?
{
"info": [{
"name": "John Smith",
"phone": "2125557878",
"country": {
"value": "USA"
}
},
{
"name": "Jane Smith",
"phone": "2125551212",
"country": {
"value": "USA"
}
},
{
"name": "Bob Jones",
"phone": "4165558714",
"country": {
"value": "Canada"
}
},
{
"name": "George Tucker",
"phone": "4454547171",
"country": {
"value": "UK"
}
},
{
"name": "Jean Normand",
"phone": "4454547171",
"country": {
"value": "France"
}
}]
}
This is what I have in groovy:
def jsonResponse = context.expand('${RESTRequest#Response}')
def parsedJson = new JsonSlurper().parseText(jsonResponse)
def info = parsedJson.info
def jsonDataObjects = []
info.each { json ->
jsonDataObjects.add(Model.buildJSONData(json))
}
I am building a collection of the elements that I need to compare to a database. How do I only add to that collection where the info.country.value = USA or Canada?
I tried using .findAll like this just to test if I could get it to filter by just one of the countries:
def info = parsedJson.info.country.findAll{it.value == "USA"}
But, when I do that, only the value field is kept. I lose the name and phone from the parse.
Thanks in advance for any assistance.
Did you try
def info = parsedJson.info.findAll{it.country.value == "USA"}
?
In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})
I am looking query the JSON data based on some where conditions for ex. list the person names whose cell no is 777-777-7777.
pl let me know what are query capabilities in JSON.
var json = [{
"name": "senthil",
"Phoneno": [{
"Home": "111-111-1111"
},
{
"Cell": "222-222-2222"
},
{
"Office": "333-333-3333"
}
],
"City": "Hartford"
},
{
"name": "kumar",
"Phoneno": [{
"Home": "444-555-6666"
},
{
"Cell": "777-777-7777"
},
{
"Office": "888-888-8888"
}
],
"City": "Austin"
},
];
var people = json.filter(function(el)
{
return el.Phoneno.some(function(number)
{
return number.Cell == "777-777-7777";
});
});
This uses the Array.filter and Array.some functions from ECMAScript 5. filter returns an array of the elements that pass a test. some returns true if any element in an array passes the test.
For browsers that don't support it, you can use the code at MDC.
This will almost certainly not be faster than the obvious for-loop approach.
As a note, if every person can have up to one phone number per type, a simpler representation would be:
"Phoneno": { "Home": "111-111-1111",
"Cell": "222-222-2222",
"Office": "333-333-3333"
}
Also, JSON technically refers to the text representation, not actual JavaScript objects.