JavaScript how to set nested json object data into single nested map - javascript

I want to set nested json data into nested map and iterate it.Consider the below sample json as example, i want to set firstName, lastName, address object, address 1 object value into single nested map.Also how to iterate it to get value from address object city field value.
Kindly provide the better solution.
Sample json:
[{
"firstName": "Jihad",
"lastName": "Saladin",
"address": {
"street": "12 Beaver Court",
"city": "Snowmass",
"state": "CO",
"zip": "81615"
},
"address1": {
"street": "16 Vail Rd",
"city": "Vail",
"state": "CO",
"zip": "81657"
}
}]

If you want to combine all the addresses, you can do the following
const people = [{
"firstName": "Jihad",
"lastName": "Saladin",
"address": {
"street": "12 Beaver Court",
"city": "Snowmass",
"state": "CO",
"zip": "81615"
},
"address1": {
"street": "16 Vail Rd",
"city": "Vail",
"state": "CO",
"zip": "81657"
}
}]
const newPeople = people.map(person => {
const addresses = [person.address]
for (let i = 1; person['address' + i]; i++) {
addresses.push(person['address' + i])
}
return {
firstName: person.firstName,
lastName: person.lastName,
addresses
}
})
console.log(JSON.stringify(newPeople))
/*
[{
"firstName": "Jihad",
"lastName": "Saladin",
"addresses": [
{
"street": "12 Beaver Court",
"city": "Snowmass",
"state": "CO",
"zip": "81615"
},
{
"street": "16 Vail Rd",
"city": "Vail",
"state": "CO",
"zip": "81657"
}
]
}]
*/

Related

accessing info from an API and displaying in h1

I have an API array I am practicing with. Below is one object from the array called users. I know in order to access the properties such as the firstName I simply write <h1> {users.firstName} </h1>. However, I am trying to display the address property within the "address" object. I thought it would be <h1> {users.address.address} </h1> but that isn't correct.
{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}
You are most likely not looping over the array. To get the user's address, you need to get every object in the users array, then you can run .address.address on each of those objects. See the snippet below:
const users = [{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}];
function App() {
return users.map(el => <h1>{el.address.address}</h1>);
}
// Render it
ReactDOM.render(<App /> , document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
It appears that you are attempting to access the usersobject.
Verify that it is an array by using the following code: const isUserArray = Array.isArray(users);
If the result is true, use a loop, such as users.map(user => <h1>{user.address.address}</h1>), to iterate through the array and access the address property of each user"

Comparing 2 arrays of nested objects while ignoring some properties in Javascript

I'm looking to check an API response for against a set of values but the API response contains some additional info that I'm not interested in checking against
Data to check:
[
{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"detail": {
"leaseholdFreehold": "Freehold",
"location": "Satisfactory",
"sector": "Office"
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
}
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "45 Headrow",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 287
},
"detail": {
"leaseholdFreehold": "Freehold",
"location": "Good",
"sector": "Residential"
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.87"
}
}
]
API response:
[
{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Satisfactory",
"sector": "Office"
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
},
"dbIdentifier": 240
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "11 Main Road",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 282
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Good",
"sector": "Residential"
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.75"
},
"dbIdentifier": 239
}
]
So I'm not interested in what values are returned for dbIdentifier, designAndCondition and developmentCompletionDate as they are not in my data to check against but I would like to compare the values for the rest of the properties. In practice these arrays will have more than 2 items
I was initially thinking I would remove the unwanted properties from the objects using the function below
const newArray = responseBody.map(({ dbIdentifierIdentifier, detail: { designAndCondition, developmentCompletionDate }, ...rest }) => rest)
Then ordering by address.uniqueIdentifier, converting to JSON strings and comparing the strings but the function above doesn't work with the nested properties as newArray doesn't contain the detail object at all
newArray:
[
{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
},
"dbIdentifier": 240
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "11 Main Road",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 282
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.75"
},
"dbIdentifier": 239
}
]
IS it possible to do it the above way by passing a destructured nested object a map function?
One way to remove the unwanted properties from the API response would be to first copy the response into a new array (to preserve the original response), then delete the properties:
const apiResponse = [{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Satisfactory",
"sector": "Office"
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
},
"dbIdentifier": 240
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "11 Main Road",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 282
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Good",
"sector": "Residential"
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.75"
},
"dbIdentifier": 239
}
]
let apiResponseCopy = JSON.parse(JSON.stringify(apiResponse))
var newArray = apiResponseCopy.map(i => {
delete i.dbIdentifier
delete i.detail.designAndCondition
delete i.detail.developmentCompletionDate
return i
})
console.log(newArray)
Then, you should be able to compare the newArray against your data.

Here API - geocode search using zipcode not returning city field

I am searching a City and state by zip code using below HERE API
https://geocode.search.hereapi.com/v1/geocode?qq=postalCode=43026&apiKey=key&in=countryCode%3AUSA,
but it's not returning city field.
the result is below
{ "items": [ { "title": "43026, OH, United States", "id": "here:cm:namedplace:22236211", "resultType": "locality", "localityType": "postalCode", "address": { "label": "43026, OH, United States", "countryCode": "USA", "countryName": "United States", "stateCode": "OH", "state": "Ohio", "postalCode": "43026" }, "position": { "lat": 39.9972, "lng": -83.15518 }, "mapView": { "west": -83.0952, "south": 39.97889, "east": -83.26074, "north": 40.06921 }, "scoring": { "queryScore": 1, "fieldScore": { "postalCode": 1 } } } ] }
can anyone please help
If you run several queries against this api, you'll notice that some results contain a city, and some do not.
For example:
If we run (with api key set to a valid value):
https://geocode.search.hereapi.com/v1/geocode?qq=postalCode=60606&apiKey=key&in=countryCode%3AUSA
We get an address like so
"address": {
"label": "60606, Chicago, IL, United States",
"countryCode": "USA",
"countryName": "United States",
"stateCode": "IL",
"state": "Illinois",
"county": "Cook",
"city": "Chicago",
"postalCode": "60606"
}
Which includes a city value.
Your query returns
"address": {
"label": "43026, OH, United States",
"countryCode": "USA",
"countryName": "United States",
"stateCode": "OH",
"state": "Ohio",
"postalCode": "43026"
},
Which is missing the city field.
You could try using the ZIP+4 code (if you have it) as mentioned in the API docs:
https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics-api/code-geocode-hpc-hsn.html
For example,
https://geocode.search.hereapi.com/v1/geocode?qq=postalCode=43026-0001&apiKey=key&in=countryCode%3AUSA
"address": {
"label": "43026-0001, Hilliard, OH, United States",
"countryCode": "USA",
"countryName": "United States",
"stateCode": "OH",
"state": "Ohio",
"county": "Franklin",
"city": "Hilliard",
"postalCode": "43026-0001"
},
Will return us a city.
NB: Not all Zip+4 codes will return a city name. For example: 43026-0101 will not (this may be because it doesn't exist)
It doesn't look to me like there is any way to guarantee a city field response with just a ZIP code.

How to remove \n from json object literal

When I write console.log(input), i get the below code but I don,t want to format it in this manner:
var contacts = { json: ' "book": {\n
"person": [\n
{\n
"firstName": "Jane",\n
"lastName": "Doe",\n
"age": "25",\n
"address": {\n
"streetAddress": "21 2nd Street",\n
"city": "Las Vegas",\n
"state": "NV",\n
"postalCode": "10021-3100"\n
}\n
},\n
{\n
"firstName": "Agatha",\n
"lastName": "Doe",\n
"age": "25",\n
"address": {\n
"streetAddress": "21 2nd Street",\n
"city": "Las Vegas",\n
"state": "NV",\n
"postalCode": "10021-3100"\n
}\n
}\n
]\n
}' }
How to convert above code in the below format?
var contacts = {
"book": {
"person": [
{
"firstName": "Jane",
"lastName": "Doe",
"age": "25",
"address": {
"streetAddress": "21 2nd Street",
"city": "Las Vegas",
"state": "NV",
"postalCode": "10021-3100"
}
},
{
"firstName": "Agatha",
"lastName": "Doe",
"age": "25",
"address": {
"streetAddress": "21 2nd Street",
"city": "Las Vegas",
"state": "NV",
"postalCode": "10021-3100"
}
}
]
}
}
When I write console.log(input), i get the below code but I don,t want to format it in this manner
(I'm going to assume input is really contacts, the thing you quoted in your question.)
The way the console formats its output depends almost entirely on the console. You can't control it directly. If you give it an object (which is what you're doing with console.log(contacts)), the implementation of the console will output that whatever way the people implementing it see fit, and it will vary from console to console — the output you see in Firefox's dev tools is different from Chrome's, and both of them are different from NodeJS's.
Most consoles will output strings in a fairly similar way (although their handling of quotes around the string varies), so you could turn your input into a string and output that. One way would be to use JSON.stringify on it:
var contacts = {
"book": {
"person": [
{
"firstName": "Jane",
"lastName": "Doe",
"age": "25",
"address": {
"streetAddress": "21 2nd Street",
"city": "Las Vegas",
"state": "NV",
"postalCode": "10021-3100"
}
},
{
"firstName": "Agatha",
"lastName": "Doe",
"age": "25",
"address": {
"streetAddress": "21 2nd Street",
"city": "Las Vegas",
"state": "NV",
"postalCode": "10021-3100"
}
}
]
}
};
console.log(JSON.stringify(contacts));
json = ' "book": {
"person": [
{
"firstName": "Jane",
"lastName": "Doe",
"age": "25",
"address": {
"streetAddress": "21 2nd Street",
"city": "Las Vegas",
"state": "NV",
"postalCode": "10021-3100"
}
},
{
"firstName": "Agatha",
"lastName": "Doe",
"age": "25",
"address": {
"streetAddress": "21 2nd Street",
"city": "Las Vegas",
"state": "NV",
"postalCode": "10021-3100"
}
}
]
}'
var contact = JSON.parse(JSON.stringify(json));
console.log(contact);

How to merge two JSON data in javascript / JQUERY

I want to merge two JSON data using Javascript or Jquery.
var object1 = [{
"id": 11,
"name": "Vasanth",
"username": "Vasanth.Rajendran",
"email": "vasanth#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
var object2 = [{
"id": 2,
"name": "Raju",
"username": "Raju.Rajendran",
"email": "Raju#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
example result:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
}];
object1 and object2 are arrays. You can use the concat method to concatenate arrays.
newObj = object1.concat(object2);
var object1 = [{
"id": 11,
"name": "Vasanth",
"username": "Vasanth.Rajendran",
"email": "vasanth#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
var object2 = [{
"id": 2,
"name": "Raju",
"username": "Raju.Rajendran",
"email": "Raju#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
var newObject = object1.concat(object2);
console.log(newObject);
Try this:
var newObj = [object1[0], object2[0]];
OR
var newObj = object1.concat(object2);
concat creates a new array consisting of the elements in the object on
which it is called, followed in order by, for each argument, the
elements of that argument (if the argument is an array) or the
argument itself (if the argument is not an array).
Reference: Array.prototype.concat()
They are arrays as I can see. You can do:
var object3 = object1.concat(object2);
//you can access your objects like this: object3[0] and object3[1]
//Or in for loop
for (i=0; i<object3.length; i++) {
console.log(object3[i]);
}
Otherwise for objects you can check
How can I merge properties of two JavaScript objects dynamically?
For reference:
var array = [] // this is array
var theObject = {} // json object
if you want to merge them into one object try:
jQuery.extend(object1[0], object2[2]);
But if you do like this all your properties will be replaced, because they are the same. That is why the above method is best for your case

Categories

Resources