JavaScript - Loop JSON array and match string in subarray - javascript

I have JSON array with subarrays and I want to loop it and find if username of user is for example 'admin'. If so then create JSON array contains data belonging to user 'admin' (region, sport, city etc). I don't have idea how to find it in loop and then slice it. I'm sorry for stupid question but I'm a little lost.
This is JSON array with structure what I have:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]
Edit:
the expected result of user 'admin' is then:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]

Loop through the array and pull out each item with a user with a username of admin:
var result = [];
var nameToSearchFor = 'admin';
for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}

One solution to your problem is to search for the index that resides the admin username. In your case is at the 0 index of the json array provided. So you can get the entire object by the index, like this:
var i = 0;
for(; i< json.length; i++){
if(json[i].user.username === "admin") break;
}
With that now you can get the object with the admin data. Like this:
json[i].user.firstName
Check this plunk here
EDIT
If you want just to get that slice to a new array perhaps then you can just slice that piece of the json array, now that you have the index.
var newArray = json.slice(i, i+1);

You can use an open source project like jinqJs to perform SQL like queries on arrays.
var data = [
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
];
var result = jinqJs()
.from(data)
.where(function(row){return row.user.username==='admin';})
.select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Related

How to shift an object on top position in existing array in javascript, if the object have some specific key

I have two array friend[] and messages[] and I have already inserted message array values in the friend array according to their friend id. Now, the main array is the friend array which includes some messages like some friends have messages and some have not. But I want to sort friend array based on the message created_Date, and those friend who have not any messages inside their object they remain same.
Here is my code:
data.sort((a, b) => (a.lastMessage ? new Date(a.lastMessage.createdAt).getTime() < new Date(b.lastMessage.createdAt).getTime() : '') ? 1 : -1)
Here is my output which is not sorted according to the last message date:
{
"data": [
{
"block": false,
"user": {
"_id": "60ed4a8c1e0812bb34674983",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
},
"friend": {
"_id": "612d11535c77de82c8a68b0d",
"profilePic": "fsjalk;gja./.coj",
"firstName": "Sachin4",
"lastName": "Kumar"
}
},
{
"block": true,
"user": {
"_id": "60ed4a8c1e0812bb34674983",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
},
"friend": {
"_id": "60ed4838ea237d0b40a16491",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
}
},
{
"block": false,
"user": {
"_id": "60ed4a8c1e0812bb34674983",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
},
"friend": {
"_id": "612d108d14521e598838690e",
"profilePic": "",
"firstName": "Sachin3",
"lastName": "Kumar"
},
"lastMessage": {
"message": "This is my sixth chat.",
"createdAt": "2021-09-06T13:47:50.082Z"
}
}
]
}
Concat elements without lastMessage to sorted elements with lastMessage using Array.filter.
Here's a minimal reproducable example
const data = getData();
const sorted = data.filter(d => d.lastMessage)
.sort((a, b) =>
new Date(a.lastMessage.createdAt) -
new Date(b.lastMessage.createdAt))
.concat(data.filter(d => !d.lastMessage));
document.querySelector(`pre`).textContent =
JSON.stringify(sorted, null, 2);
function getData() {
return [
{
"user": {
"_id": "60ed4a8c1e0812bb34674983",
}
},
{
"user": {
"_id": "60ed4a8c1e0812bb34674983",
},
"lastMessage": {
"createdAt": "2021-09-06T13:47:50.082Z"
}
},
{
"user": {
"_id": "60ed4a8c1e0812bb34674983",
},
},
{
"user": {
"_id": "60ed4a9c140e19bb34674983",
},
"lastMessage": {
"createdAt": "2020-04-02T23:11:12.154Z"
}
},
];
}
<pre></pre>

Postman - Looping through an array of nested objects to make a variable

I am trying to set a variable from following phone number with value: “+33652556777” (index 4 in JSON attached below) which is the last object in contacts (index 4).
To do so is pretty simple:
let jsonData = pm.response.json();
console.log (jsonData.contacts[4].phone_numbers[0].value)
const PhoneNumber = jsonData.contacts[4].phone_numbers[0].value
pm.environment.set("Jacky", PhoneNumber);
Since I have to use different query parameters to filter by eg. created_at=asc, desc, the property of the phone_numbers order might change index number and I won’t be able to fetch desire phone number "+33652556777” instead it will set a different phone number which I cannot allow.
I know there is way to fetch our number and make it variable for next requests, which is iterating over properties or keys in the object “ for….in or for…of ” but for some reason I cannot achieve it.
What I could achieve is to get through first object “contacts” but impossible to get to its nested array “phone_numbers”. Here is how I did it:
let jsonData = pm.response.json();
let contact;
for (let filter of jsonData.contacts){
if (filter.last_name == "Rowland"){
contact = filter;
}}
console.log (contact);
Could you please help?
Here goes the JSON body response:
{
"contacts": [
{
"id": 11121211,
"direct_link": "https://example.example",
"first_name": "test1",
"last_name": "test",
"company_name": "test",
"information": null,
"is_shared": true,
"created_at": 1582798926,
"updated_at": 1582798926,
"emails": [],
"phone_numbers": [
{
"id": 60065270,
"label": "Work",
"value": "+33134567666"
}
]
},
{
"id": 22222222,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686067,
"updated_at": 1583686067,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567899"
}
]
},
{
"id": 33333564,
"direct_link": "https://example.example",
"first_name": "Jessica",
"last_name": "Biel",
"company_name": "N-Sync",
"information": null,
"is_shared": true,
"created_at": 1583686086,
"updated_at": 1583686086,
"emails": [],
"phone_numbers": []
},
{
"id": 45678901,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686105,
"updated_at": 1583686105,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567333"
}
]
},
{
"id": 56789123,
"direct_link": "https://example.example",
"first_name": "Jacky",
"last_name": "Rowland",
"company_name": "Test Company1",
"information": "",
"is_shared": true,
"created_at": 1583745888,
"updated_at": 1608556499,
"emails": [
{
"id": 76594398,
"label": "Work",
"value": "mandatory_field#example.com"
}
],
"phone_numbers": [
{
"id": 60650277,
"label": "Mobile",
"value": "+33652556777"
}
]
}
],
"meta": {
"count": 6,
"total": 241,
"current_page": 1,
"per_page": 5,
"next_page_link": "https://example.example",
"previous_page_link": null
}
}
You could use something basic like this:
_.each(pm.response.json().contacts, (contact) => {
if(contact.last_name === "Rowland") {
pm.environment.set(`${contact.first_name}_${contact.last_name}_number`, contact.phone_numbers[0].value)
}
})
There are probably better and more performant ways to do this but if you just want to set a variable for that contact, no matter where they are in the response - This would work :D
you can use forEach or _.each as danny mentioned to get all numbers else use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers[0].value)
use array.find to find the contact with first_name jacky adn then get phone_number[0].value from it.
if you want all numbers from that array then use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers.map((a)=>a.value))
here we map the result to get only the numbers from phone_number array.
is it what you looking for !?

Javascript array value undefined?

I am currently working on a REST API / website project, where my REST API has to return an array of objects from the server, via a response and using GSON to make a Json array out of the data. However, when trying to get values from the javascript array for the website, I keep getting undefined. This is the array:
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [
{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}
],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [
{
"id": 1,
"number": "123124",
"info": "0x1"
}
]
}
];
When I try to call userArr[0].firstName, I get an error saying that it's undefined, even though the data is there. This is from a get call, which I am doing in my javascript from my REST API, which sends back this specific array. I have tried looping through the array, with multiple objects inside, however I am unable to retrieve any info at all.
Your userArr is an array of objects which do not have firstName property. They have only one property named 0x1 for some reason. And this 0x1 property has firstName property.
You can access firstName of 0x1 property using this notation:
userArr[0]["0x1"].firstName
Here is the working demo:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0]["0x1"].firstName);
By the way, there is a missing closing } bracket in the end of the array in your code.
I think if you write this code this way it is easy to understand and find the problem
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{"id": 1,"name": "Fodbold","people": ["0x1"]}],
"id": 1,
"address": {"id": 1,"street": "Street1","cityInfo": {"id": 1,"zipCode": "0555","city": "Scanning"},
"infoList": ["0x1","0x2"]},
"phones": [{"id": 1,"number": "123124","info": "0x1"}]
}
}
];
You also missing the last second bracket.
Then you could use this console.log(userArr[0]["0x1"].firstName);
try this one
userArr[0]["0x1"].firstName
Incase value "0x1" is dynamic, you can access it by using Object.keys(userArr[0])[0] to get the first key of the object.
Here is solution:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0][Object.keys(userArr[0])[0]].firstName);

Checking a value in a nested JSON using Postman

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
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

How to Sort the JSON array in the controller of AngularJS?

Kindly help me in sorting the below JSON list in the controller and display in the view.
Actually orderBy filter sorting one level, But I need it sort even for childs recursively.
Input:
R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1
Output:
R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4
Please find the sample in Plunker.
http://plnkr.co/edit/JslHwJ1CBREKf6FgYHaZ?p=preview
var sortNames = function(arr){
arr = arr.sort(function(a,b){
return a.name > b.name;
})
for (var i = 0; i < arr.length; i++){
if (arr[i].childs){
sortNames(arr[i].childs)
}
}
return arr;
}
var names = [
{
"name": "Root1",
"Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
"status": "",
"dispName": "",
"imageURL": "",
"childCount": "",
"childs": [
{
"name": "Sub1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
"childs": [
{
"name": "Template1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
"status": "",
"dispName": "",
"imageURL": ""
},
{
"name": "Template2",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
"status": "",
"dispName": "",
"imageURL": ""
}
]
},
{
"name": "Template3",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"
}
]
},
{
"name": "Root2",
"Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
"childs": [
{
"name": "Sub2",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
"childs": [
{
"name": "Template4",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
},
{
"name": "Template5",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
}
]
}
]
}
];
sortNames(names);

Categories