Here i have got array of objects data, from this data i need to delete the element based on a value, if value is found then delete entire element
let value = "/unifiedconfig/config/agent/5197";
//if this found in json data i have delete complete element{"refURL":"/unifiedconfig/config/agent/5197","agentId":"1085","firstName":"Owen","lastName":"Harvey","userName":"oharvey"}
var myjsonobj = {
"refURL": "/unifiedconfig/config/agentteam/5022",
"changeStamp": 12,
"agentCount": 7,
"description": "Cumulus Outbound Team",
"name": "CumulusOutbound",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [{
"agent": [{
"refURL": "/unifiedconfig/config/agent/5197",
"agentId": "1085",
"firstName": "Owen",
"lastName": "Harvey",
"userName": "oharvey"
}, {
"refURL": "/unifiedconfig/config/agent/5201",
"agentId": "1320",
"firstName": "Bruce",
"lastName": "Wayne",
"userName": "bwayne"
}, {
"refURL": "/unifiedconfig/config/agent/5202",
"agentId": "1321",
"firstName": "Peter",
"lastName": "Parker",
"userName": "pparker"
}, {
"refURL": "/unifiedconfig/config/agent/5203",
"agentId": "1322",
"firstName": "Tony",
"lastName": "Stark",
"userName": "tstark"
}, {
"refURL": "/unifiedconfig/config/agent/5204",
"agentId": "1323",
"firstName": "Steve",
"lastName": "Rogers",
"userName": "srogers"
}, {
"refURL": "/unifiedconfig/config/agent/5205",
"agentId": "1324",
"firstName": "Bruce",
"lastName": "Banner",
"userName": "bbanner"
}, {
"refURL": "/unifiedconfig/config/agent/5231",
"agentId": "1086",
"firstName": "Annika",
"lastName": "Hamilton",
"userName": "annika"
}, {
"refURL": "/unifiedconfig/config/agent/5118",
"agentId": "1317",
"firstName": "Donald",
"lastName": "Duckling",
"userName": "dduck"
}]
}],
"supervisors": [{
"supervisor": [{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}]
}]
}
Object.keys(myjsonobj).forEach(function(key) {
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(JSON.stringify(myjsonobj));
This should do the trick:
var myjsonobj = {"refURL": "/unifiedconfig/config/agentteam/5022","changeStamp": 12,"agentCount": 7,"description": "Cumulus Outbound Team","name": "CumulusOutbound","peripheral": {"id": 5000,"name": "CUCM_PG_1"},"peripheralId": 5000,"supervisorCount": 1,"agents": [{"agent": [{"refURL": "/unifiedconfig/config/agent/5197","agentId": "1085","firstName": "Owen","lastName": "Harvey","userName": "oharvey"}, {"refURL": "/unifiedconfig/config/agent/5201","agentId": "1320","firstName": "Bruce","lastName": "Wayne","userName": "bwayne"}, {"refURL": "/unifiedconfig/config/agent/5202","agentId": "1321","firstName": "Peter","lastName": "Parker","userName": "pparker"}, {"refURL": "/unifiedconfig/config/agent/5203","agentId": "1322","firstName": "Tony","lastName": "Stark","userName": "tstark"}, {"refURL": "/unifiedconfig/config/agent/5204","agentId": "1323","firstName": "Steve","lastName": "Rogers","userName": "srogers"}, {"refURL": "/unifiedconfig/config/agent/5205","agentId": "1324","firstName": "Bruce","lastName": "Banner","userName": "bbanner"}, {"refURL": "/unifiedconfig/config/agent/5231","agentId": "1086","firstName": "Annika","lastName": "Hamilton","userName": "annika"}, {"refURL": "/unifiedconfig/config/agent/5118","agentId": "1317","firstName": "Donald","lastName": "Duckling","userName": "dduck"}]}],"supervisors": [{"supervisor": [{"refURL": "/unifiedconfig/config/agent/5174","agentId": "1082","firstName": "Rick","lastName": "Barrows","userName": "rbarrows#dcloud.cisco.com"}]}]}
let value = "/unifiedconfig/config/agent/5197";
myjsonobj.agents[0].agent=myjsonobj.agents[0].agent.filter(a=>a.refURL!=value);
console.log(myjsonobj)
From your data it looks pretty obvious that the target value can only be found in the refURL property of the agent-elements. So this is what I focused on in the above script.
Related
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>
I have to search through some JSON data looking for matches from an input form. Here is what I have so far:
<div class="container">
<form id="searchForm" class="form-group">
<input type="text" id="searchText" class="form-control />
</form>
</div>
Here's my JS ...
let searchForm = document.getElementById('searchForm');
searchForm.addEventListener('submit', function(e){
e.preventDefault();
let searchText = document.getElementById('searchText').value;
getCharacters(searchText);
});
function getCharacters(searchText){
let xhr = new XMLHttpRequest();
xhr.open('GET', 'characters.json', true);
xhr.onload = function(){
if(this.status == 200){
let characters = JSON.parse(this.responseText);
let output = '';
for(let i in characters){
output +=
...
;
}
document.getElementById('characters').innerHTML = output;
}
}xhr.onerror = function(){
console.log('Request error');
}xhr.send();
};
And my JSON ...
[
{
"id": 1001,
"first_name": "Rick",
"last_name": "Grimes",
"img": "https://ia.media-imdb.com/images/M/MV5BMjI2NDYyNjg4NF5BMl5BanBnXkFtZTcwMjI5OTMwNA##._V1_.jpg",
"career": "Sheriff",
"actor": "Andrew Lincoln",
"still_alive": true,
"tags": ["rick","grimes","sheriff","andrew","lincoln","alive"]
},
{
"id": 1002,
"first_name": "Daryl",
"last_name": "Dixon",
"img": "https://ia.media-imdb.com/images/M/MV5BMTQ5ODE4NTgzMl5BMl5BanBnXkFtZTcwODI0MjAwMw##._V1_.jpg",
"career": "unknown",
"actor": "Norman Reedus",
"still_alive": true,
"tags": ["daryl","dixon","unknown","norman","reedus","alive"]
},
{
"id": 1003,
"first_name": "Glenn",
"last_name": "Rhee",
"img": "https://ia.media-imdb.com/images/M/MV5BMTcxODE2MDgxOF5BMl5BanBnXkFtZTgwNjk2MDM1NzE#._V1_.jpg",
"career": "Nerd",
"actor": "Steven Yeun",
"still_alive": false,
"tags": ["glenn","rhee","nerd","steven","yeun","dead"]
}
]
Within the JS I am looking for a way to use the searchText to query the JSON based on either first_name, last_name or tags. From there I will output the matching data into a div for each match.
Need help with the query part! Everything else I have working but I'm stuck at this point. All help is greatly appreciated!
First parse it from JSON to JS object then filter it
let objectsFromXHR = JSON.parse(`[
{
"id": 1001,
"first_name": "Rick",
"last_name": "Grimes",
"img": "https://ia.media-imdb.com/images/M/MV5BMjI2NDYyNjg4NF5BMl5BanBnXkFtZTcwMjI5OTMwNA##._V1_.jpg",
"career": "Sheriff",
"actor": "Andrew Lincoln",
"still_alive": true,
"tags": ["rick","grimes","sheriff","andrew","lincoln","alive"]
},
{
"id": 1002,
"first_name": "Daryl",
"last_name": "Dixon",
"img": "https://ia.media-imdb.com/images/M/MV5BMTQ5ODE4NTgzMl5BMl5BanBnXkFtZTcwODI0MjAwMw##._V1_.jpg",
"career": "unknown",
"actor": "Norman Reedus",
"still_alive": true,
"tags": ["daryl","dixon","unknown","norman","reedus","alive"]
},
{
"id": 1003,
"first_name": "Glenn",
"last_name": "Rhee",
"img": "https://ia.media-imdb.com/images/M/MV5BMTcxODE2MDgxOF5BMl5BanBnXkFtZTgwNjk2MDM1NzE#._V1_.jpg",
"career": "Nerd",
"actor": "Steven Yeun",
"still_alive": false,
"tags": ["glenn","rhee","nerd","steven","yeun","dead"]
}
]`);
const target = 'Glenn'
console.log(objectsFromXHR.filter(each => each.first_name === target));
It filter function you can use Regex etc. Just return true to let JS know this currect filtering object is valid
To search by first and last name, you can combine 2 string and then cast it to lowercase, and then compare with your inputs.
I added an empty string at the end in case both fields are empty.
This method is case-insensitive and removes empty inputs in front and end.
const obj = [
{
"id": 1001,
"first_name": "Rick",
"last_name": "Grimes",
"img": "https://ia.media-imdb.com/images/M/MV5BMjI2NDYyNjg4NF5BMl5BanBnXkFtZTcwMjI5OTMwNA##._V1_.jpg",
"career": "Sheriff",
"actor": "Andrew Lincoln",
"still_alive": true,
"tags": ["rick","grimes","sheriff","andrew","lincoln","alive"]
},
{
"id": 1002,
"first_name": "Daryl",
"last_name": "Dixon",
"img": "https://ia.media-imdb.com/images/M/MV5BMTQ5ODE4NTgzMl5BMl5BanBnXkFtZTcwODI0MjAwMw##._V1_.jpg",
"career": "unknown",
"actor": "Norman Reedus",
"still_alive": true,
"tags": ["daryl","dixon","unknown","norman","reedus","alive"]
},
{
"id": 1003,
"first_name": "Glenn",
"last_name": "Rhee",
"img": "https://ia.media-imdb.com/images/M/MV5BMTcxODE2MDgxOF5BMl5BanBnXkFtZTgwNjk2MDM1NzE#._V1_.jpg",
"career": "Nerd",
"actor": "Steven Yeun",
"still_alive": false,
"tags": ["glenn","rhee","nerd","steven","yeun","dead"]
}
];
function searchByName(data, str) {
return data.filter(i => {
const pool = i.first_name + i.last_name + '';
return pool.toLowerCase().includes(str.trim().toLowerCase());
});
}
console.log(searchByName(obj, 'Rhe'));
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>
return res.send({"user": user});
the user object returned is like this(see below), but I want to hide the password, confirmationToken and also the __v fields.
{
"user": {
"_id": "566786",
"detail": {
"lastUpdate": "2015-01-22T22:06:22.951Z",
"registrationDate": "2015-01-22T02:15:07.379Z",
"firstName": "Testing",
"lastName": "Testing",
},
"info": {
"confirmationToken": "3dc917fbfd6f47e",
"password": "$2a$08$4ugeIPC.5nCMQiyutL11i",
"email": "testing#abcdefgxxxxxx.com",
}
},
}
I want it to be like this:
{
"user": {
"_id": "566786",
"detail": {
"lastUpdate": "2015-01-22T22:06:22.951Z",
"registrationDate": "2015-01-22T02:15:07.379Z",
"firstName": "Testing",
"lastName": "Testing",
},
"info": {
"email": "testing#abcdefgxxxxxx.com",
}
},
}
How should I filter out those fields that I don't want?
Just remove the properties by deleting them
delete user.user.info.password;
delete user.user.info.confirmationToken;
return res.send({"user": user});
I'm fairly new to YUI and facing an issue while trying to create a YUI3 DataTable from the below JSON -
{
"generations": [
{
"type": "Modern",
"showName": "The Modern Generation",
"imgURI": "file:/D:/projectGen.png",
"relations": {
"father": {
"age": "49",
"firstName": "George",
"lastName": "Mathews",
"priority": "1",
"profession": "Service"
},
"mother": {
"age": "47",
"firstName": "Susan",
"lastName": "Aldrin",
"priority": "2",
"profession": "Home-Maker"
},
"brother": {
"age": "28",
"firstName": "Martin",
"lastName": "Mathews J",
"priority": "3",
"profession": "Engineer"
},
"sister": {
"age": "23",
"firstName": "Laura",
"lastName": "Mathews J",
"priority": "4",
"profession": "Fashion Model"
}
}
}
]
}
The table which I need to create should look like the one below -
Any info on how can I do this?
A JSFiddle would be appreciated.
I hope this helps. http://jsfiddle.net/BM3kX/2/
HTML:
<div class="yui3-skin-sam" id="datatable"></div>
Javascript:
YUI().use('datatable', 'datasource-local', 'datasource-jsonschema',function(Y){
var data = {};//JSON here
var localDataSource = new Y.DataSource.Local({source:data});
localDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: 'generations',
resultFields: [{key:'showName'},
{
key:'father',
locator:'relations.father.firstName'
},
{
key:'mother',
locator:'relations.mother.firstName'
},
{
key:'brother',
locator:'relations.brother.firstName'},
{
key:'sister',
locator:'relations.sister.firstName'
}]
}
});
var table = new Y.DataTable({
columns: ["showName", "father","mother","brother","sister"]
});
table.plug(Y.Plugin.DataTableDataSource, {
datasource: localDataSource
});
table.render('#datatable');
table.datasource.load();
});