I have 2 or more objects in Main Object.
How can I find one object againt this key value.
{
"0": {
"component": "AWAY",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
},
},
"1": {
"component": "PHONE_BOTH",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
}
},
"2": {
"component": "MEETING_ROOM",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": true,
"image": ""
}
}
}
I just want to get one object where inRoom = true
It is not recommended to index an object with numeric keys. Use an array instead then you can use filter directly on the array
const arr = [{
"component": "AWAY",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
},
},
{
"component": "PHONE_BOTH",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
}
},
{
"component": "MEETING_ROOM",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": true,
"image": ""
}
}
]
console.log(arr.filter(({currentUser}) => currentUser.inRoom === true))
You should convert your dictionary to an array and then find the object by a specific criteria using the find() array method. See implementation:
// usersDict is the given Main Object
// convert usersDict to array of user objects
let usersArray = Object.values(usersDict);
// find user which has inRoom flag true
let userInRoom = usersArray.find(o => !!o.currentUser.inRoom);
var bb = {
"0": {
"component": "AWAY",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
},
},
"1": {
"component": "PHONE_BOTH",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
}
},
"2": {
"component": "MEETING_ROOM",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": true,
"image": ""
}
}
}
var kk = []
for (const man in bb) {
if(bb[man].currentUser.inRoom){
kk.push({man: bb[man]})
}
}
console.log(kk.length ? kk[0] : {})
First, you should convert your object to an array then use the filter method in the array:
// obj = your data
Object.values(obj).filter(obj => obj.currentUser.inRoom)
Related
I'm trying to filter the 2nd level of array and if it is true will get the 1st level array in JSON data. I'm using jQuery grep to find the specific element of an array and to filter the department and the jobs.title.
In my case I'm trying to search job title "FULL" and the data is under the department of Marketing. So I'm trying to achieve that if the data "FULL" exist under Marketing Department then Display Marketing Department Jobs.
For JSON file I'm using greenhouse API for testing.
{
"departments": [
{
"id": 4009377006,
"name": "Client Success",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009378006,
"name": "Creative",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009379006,
"name": "Engineering",
"parent_id": null,
"child_ids": [],
"jobs": [
{
"absolute_url": "https://boards.greenhouse.io/frequence/jobs/4044313006",
"data_compliance": [
{
"type": "gdpr",
"requires_consent": false,
"retention_period": null
}
],
"internal_job_id": 4034527006,
"location": {
"name": "Menlo Park, CA"
},
"metadata": [
{
"id": 4410278006,
"name": "Desired Timezones",
"value": [],
"value_type": "multi_select"
}
],
"id": 4044313006,
"updated_at": "2023-02-02T13:40:43-05:00",
"requisition_id": "TEST101",
"title": "TEST HIRING - SOFTWARE ENGINEER"
}
]
},
{
"id": 4009380006,
"name": "Finance",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009381006,
"name": "Marketing",
"parent_id": null,
"child_ids": [],
"jobs": [
{
"absolute_url": "https://boards.greenhouse.io/frequence/jobs/4044533006",
"data_compliance": [
{
"type": "gdpr",
"requires_consent": false,
"retention_period": null
}
],
"internal_job_id": 4034679006,
"location": {
"name": "Menlo Park, CA, or New York City, NY, or Washington DC"
},
"metadata": [
{
"id": 4410278006,
"name": "Desired Timezones",
"value": [],
"value_type": "multi_select"
}
],
"id": 4044533006,
"updated_at": "2023-02-02T13:40:43-05:00",
"requisition_id": "TEST103",
"title": "TEST HIRING - FULL STACK DEVELOPER"
},
{
"absolute_url": "https://boards.greenhouse.io/frequence/jobs/4044315006",
"data_compliance": [
{
"type": "gdpr",
"requires_consent": false,
"retention_period": null
}
],
"internal_job_id": 4034529006,
"location": {
"name": "Menlo Park, CA, or New York City, NY, or Washington DC"
},
"metadata": [
{
"id": 4410278006,
"name": "Desired Timezones",
"value": [],
"value_type": "multi_select"
}
],
"id": 4044315006,
"updated_at": "2023-02-02T13:40:43-05:00",
"requisition_id": "TEST102",
"title": "TEST HIRING - PHP DEVELOPER"
}
]
},
{
"id": 4009382006,
"name": "Operations",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009383006,
"name": "People",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009384006,
"name": "Product",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 4009385006,
"name": "Sales",
"parent_id": null,
"child_ids": [],
"jobs": []
},
{
"id": 0,
"name": "No Department",
"parent_id": null,
"child_ids": [],
"jobs": []
}
]
}
This is what I've been working below.
$.getJSON('https://boards-api.greenhouse.io/v1/boards/frequence/departments/',
function(data) {
var search_term = 'FULL';
var search = search_term.toUpperCase();
var getDepartment = '';
var filterDept = $.grep(data.departments, function (element, index) {
var search_filter = element.name.toUpperCase().indexOf(search) >= 0;
console.log(element);
if(search_filter <= 0){
// I'm trying to achieve here is to check if the element exist in 2nd level of array
//and if true it will retrieve the parent array or 1st level of array.
filterDept = $.grep(element.jobs, function (element1, index1) {
search_filter = element1.title.toUpperCase().indexOf(search) >= 0;
if(search_filter == true) {
search_filter = element.name.toUpperCase().indexOf(search) >= 0;
console.log(element1.title);
return false;
}
});
}
return search_filter;
});
console.log(filterDept);
});
Here is the way I would approach this:
const search_term = 'FULL';
const search = search_term.toUpperCase();
// Use helpful names like "department" and "job" instead of
// "element" and "element1" - this improves readability.
const matches = $.grep(data.departments, function (department) {
const isMatch = department.name.toUpperCase().indexOf(search) >= 0;
// Return `true` early if we have a direct name match.
if (isMatch) { return true; }
// If we haven't matched directly on name, we will filter
// the department's jobs for matches.
const jobMatches = $.grep(department.jobs, function (job) {
return job.title.toUpperCase().indexOf(search) >= 0;
});
// We consider this department to be a match if its filtered
// jobs has any elements (ie., its `.length` is greater than 0).
return jobMatches.length > 0;
});
I have created a fiddle for reference.
Update
I feel I should add that I used jQuery's grep function in my example only because it was mentioned in the question.
I would not use jQuery for this functionality because modern JavaScript has the methods on the Array prototype to do the filtering we require.
Here is an example in plain JavaScript:
const search_term = 'FULL';
const search = search_term.toUpperCase();
const matches = data.departments.filter(department => {
const isMatch = department.name.toUpperCase().indexOf(search) >= 0;
return isMatch || department.jobs.some(job => job.title.toUpperCase().indexOf(search) >= 0);
});
And here is a fiddle that uses this code.
I have a JSON like this, how to get the value of StatusDescription? I tried many times but the result is undefined. Here is my JSON:
{
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
I'm using in my NodeJS app, like myapp.js, and console.log()
Try this
I stored your sample json in variable json
var json = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
Accessed it like below
console.log(json.data.items[0].origin_info.trackinfo[0].StatusDescription);
Items is an array and we took array element 0.
trackinfo again is an array and we took array element 0.
We can change array index or loop through and get required values.
You have to iterate through your items and trackinfo to get to StatusDescription. Try this one.
const data = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
const items = data.data.items.map(item => item)
const trackinfo = items.map(item => item.origin_info.trackinfo).flat()
console.log(trackinfo)
const statusDescription = trackinfo.map(trackinfo => trackinfo.StatusDescription)
console.log(statusDescription)
Regardless of the JSON object structure (simple or complex) what would be the ideal method to extract all urls from the following object into an array to iterate over in Javascript?
{
"url": "https://example.com:443/-/media/images/site/info",
"data": [
{
"id": "da56fac6-6907-4055-96b8-f8427d4c64fd",
"title": "AAAA 2021",
"time": "",
"dateStart": "2021-03-01T08:00:00Z",
"dateEnd": "2021-12-31T15:00:00Z",
"address": "",
"geo": {
"longitude": "",
"latitude": "",
"mapExternalLink": ""
},
"price": "Free Admission",
"masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"showDateInfo": false,
"showDateInfoOnListings": false,
"showTimeInfo": false,
"showTimeInfoOnListings": false,
"tags": [
{
"key": "Lifestyle",
"name": "Lifestyle"
}
],
"partnerName": "",
"sort_data": {
"recommended": 0,
"recent": 3,
"partner": 0,
"popular": 0
}
}
]
}
I would like to get the results in an array such as:
[
https://example.com:443/-/media/images/site/info,https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx, https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx
]
I gather that i would need to apply some regex to extract the urls but not sure how to treat the json object as string for regex processing?
I think the better and easier way is to stringfy given json into string and solve it by regex.
But still if you need to solve it by recursive, try the codes below:
const obj = {
url: "https://example.com:443/-/media/images/site/info",
data: [
{
id: "da56fac6-6907-4055-96b8-f8427d4c64fd",
title: "AAAA 2021",
time: "",
dateStart: "2021-03-01T08:00:00Z",
dateEnd: "2021-12-31T15:00:00Z",
address: "",
geo: {
longitude: "",
latitude: "",
mapExternalLink: "",
},
price: "Free Admission",
masonryImage:
"https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
image: "https://tw.yahoo.com",
showDateInfo: false,
showDateInfoOnListings: false,
showTimeInfo: false,
showTimeInfoOnListings: false,
tags: [
{
key: "Lifestyle",
name: "Lifestyle",
link: "https://www.google.com",
},
],
partnerName: "",
sort_data: {
recommended: 0,
recent: 3,
partner: 0,
popular: 0,
anotherObj: {
link: "https://www.github.com",
},
},
},
],
};
function getUrl(obj) {
const ary = [];
helper(obj, ary);
return ary;
}
function helper(item, ary) {
if (typeof item === "string" && isUrl(item)) {
ary.push(item);
return;
} else if (typeof item === "object") {
for (const k in item) {
helper(item[k], ary);
}
return;
}
return null;
}
function isUrl(str) {
if (typeof str !== "string") return false;
return /http|https/.test(str);
}
console.log(getUrl(obj));
But if you use this solution you need to transfer your json into js object
i'd agree to use a JSON parser, but if you want to do it with a regular expression, you might try this
console.log(JSON.stringify({
"url": "https://example.com:443/-/media/images/site/info",
"data": [{
"id": "da56fac6-6907-4055-96b8-f8427d4c64fd",
"title": "AAAA 2021",
"time": "",
"dateStart": "2021-03-01T08:00:00Z",
"dateEnd": "2021-12-31T15:00:00Z",
"address": "",
"geo": {
"longitude": "",
"latitude": "",
"mapExternalLink": ""
},
"price": "Free Admission",
"masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"showDateInfo": false,
"showDateInfoOnListings": false,
"showTimeInfo": false,
"showTimeInfoOnListings": false,
"tags": [{
"key": "Lifestyle",
"name": "Lifestyle"
}],
"partnerName": "",
"sort_data": {
"recommended": 0,
"recent": 3,
"partner": 0,
"popular": 0
}
}]
}).match(/(?<=")https?:\/\/[^\"]+/g));
(?<=")https?:\/\/[^\"]+ basically finds patterns that start with a protocol scheme (http:// or https:// preceded by a " character) followed by anything that is not "
I am trying to develop a dynamic DraggableFlatList with react native redux, where the updated array from onDragEnd is dispatched to the store. Hence I am trying to create a function where I use the "from" and "to" parameters from the return object from onDragEnd to alter a new array before dispatch. As an example, in the object below, I work with three items, that are objects from the array:
Object {
"data": Array [
Object {
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
},
Object {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
},
Object {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
},
],
"from": 2,
"to": 1,
}
Here I would like the object with the description "two" to change place with the object with the description "one." The keys don't matter because I give them new keys when I render during render.
The function that is doing the replacement looks like this so far:
const dragComplete = (item) => {
let itemArray = item.data;
// from object is going to be replaced with to object and visa vreca
let indexFrom = item.from;
let indexTo = item.to;
let objMovesFrom = itemArray[indexFrom];
let objMovesTo = itemArray[indexTo];
let sortedArray = itemArray;
console.log('Object moves from : ' + objMovesFrom.description);
console.log('Obejct moves to : ' + objMovesTo.description);
sortedArray.map((task, i) => {
if ((i = indexFrom)) {
sortedArray.splice(indexFrom, 1, objMovesTo);
}
if ((i = indexTo)) {
sortedArray.splice(indexTo, 1, objMovesFrom);
}
});
console.log(item);
//dispatch(setTaskList(item.data));
};
I haven't figured to make any sense of it yet...
Thx for the helpful answers!
How about just simply swapping items?..
const dragComplete = item => {
const {
from: sourceIndex,
to: targetIndex,
data: dragList,
} = item;
// // shallow `item.data` copy for a non mutating approach.
// const swapList = Array.from(dragList);
const dragItem = dragList[sourceIndex]; // swapList[sourceIndex];
const swapItem = dragList[targetIndex]; // swapList[targetIndex];
// simply swap items.
// actively mutate `item.data`. // // `item.data` remains unmutated.
dragList[targetIndex] = dragItem; // swapList[targetIndex] = dragItem;
dragList[sourceIndex] = swapItem; // swapList[sourceIndex] = swapItem;
console.log('Object moves from : ' + dragItem.description);
console.log('Object moves to : ' + swapItem.description);
// return swapList;
};
const sample = {
"data": [{
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
}, {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
}, {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
}],
"from": 2,
"to": 1,
};
console.log({ data: sample.data });
dragComplete(sample);
console.log({ data: sample.data });
.as-console-wrapper { min-height: 100%!important; top: 0; }
This is my json:
{
"senderName": "ifelse",
"message": "Hi",
"groups": [
{
"id": 14,
"groupname": "Angular",
"contactgroups": [
{
"id": 1,
"contact": {
"id": 1,
"gsm": "123456789"
}
},
{
"id": 3,
"contact": {
"id": 2,
"gsm": "111111111"
}
}],
"select": true
}],
"draftData": {
"contacts": [
]
}
}
How to make the above json into:
[{phoneno: 123456789; sender: ifelse ; message: Hi},{phoneno: 11111111; sender: ifelse ; message: Hi}]
I want to take phoneno data from gsm object key
Which is best method to do this? for or forEach or anyother?
I guess, this is what you want. Use map to convert contactgroups to new array with phoneno.
var data = {
"senderName": "ifelse",
"message": "Hi",
"groups": [{
"id": 14,
"groupname": "Angular",
"contactgroups": [{
"id": 1,
"contact": {
"id": 1,
"gsm": "123456789"
}
},
{
"id": 3,
"contact": {
"id": 2,
"gsm": "111111111"
}
}
],
"select": true
}],
"draftData": {
"contacts": []
}
}
var result = data.groups[0].contactgroups.map(i => {
return {
phoneno: i.contact.gsm,
sender: data.senderName,
message: data.message
}
})
console.log(result);