How can I get the id of info1 or info2 with each information of the inside loop by jquery loop. Fo example I want to get id 1 from info1 then all the information within id 1 similarly same as from info2. I need the output to show in the browser.
var data = {
"info1": {
"1": {
"clientname": "ruhul yahoo",
"clientemail": "ruhul080#yahoo.com",
"clientusername": "ruhulya"
},
"2": {
"clientname": "kaosar yahoo",
"clientemail": "kaosar080#yahoo.com",
"clientusername": "kaosar"
}
},
"info2": {
"3": {
"id": "24",
"receiver": "5",
"content": "chat system",
"time": "2015-08-19 12:09:19"
},
"4": {
"id": "23",
"receiver": "4",
"content": "chat system",
"time": "2015-08-19 12:09:19"
}
},
}
Thanks in advance.
Iterate the json array and access the object like the following code.
var data = {
"info1": {
"1": {
"clientname": "ruhul yahoo",
"clientemail": "ruhul080#yahoo.com",
"clientusername": "ruhulya"
},
"2": {
"clientname": "kaosar yahoo",
"clientemail": "kaosar080#yahoo.com",
"clientusername": "kaosar"
}
},
"info2": {
"3": {
"id": "24",
"receiver": "5",
"content": "chat system",
"time": "2015-08-19 12:09:19"
},
"4": {
"id": "23",
"receiver": "4",
"content": "chat system",
"time": "2015-08-19 12:09:19"
}
},
};
for(var j in data){
for(var k in data[j]){
console.log(data[j][k]);
}
}
Your browser's Console will log the following objects if you run the above example.
Object {clientname: "ruhul yahoo", clientemail: "ruhul080#yahoo.com", clientusername: "ruhulya"}
Object {clientname: "kaosar yahoo", clientemail: "kaosar080#yahoo.com", clientusername: "kaosar"}
Object {id: "24", receiver: "5", content: "chat system", time: "2015-08-19 12:09:19"}
Object {id: "23", receiver: "4", content: "chat system", time: "2015-08-19 12:09:19"}
Then you can access the values like a normal object console.log(data[j][k].clientname);
This function will find you the first instance of a variable name in the object. If you need to find a variable in a specific path you could amend this function fairly easily to do that. Certainly the function as is passes the test case you've provided.
function findVar(data, varName) {
for (var i in data) {
if (i === varName) return data[i];
if (typeof (data[i]) === 'object') {
var findResult = findVar(data[i], varName)
if (typeof(findResult) !== 'undefined')
{
return findResult;
}
}
}
return undefined;
}
Firstly, This is not a valid JSON, Rmove the last , before last {
Secondly , parse it as a JSON and get the info as
data.info1[1].clientname
var data = JSON.parse('{"info1":{"1":{"clientname":"ruhul yahoo","clientemail":"ruhul080#yahoo.com","clientusername":"ruhulya"},"2":{"clientname":"kaosar yahoo","clientemail":"kaosar080#yahoo.com","clientusername":"kaosar"}},"info2":{"3":{"id":"24","receiver":"5","content":"chat system","time":"2015-08-19 12:09:19"},"4":{"id":"23","receiver":"4","content":"chat system","time":"2015-08-19 12:09:19"}}}');
alert(data.info1[1].clientname);
alert(data.info1[2].clientname);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can iterate over this object like this
for(var i in data){
for(var j in data[i]){
console.log(data[i][j]);
}
}
Related
i want to filter the given below array on the basis of dynamic values (name and section).
var allResponse = [
{
"name": "ABC",
"class": "8",
"section": "A",
},
{
"name": "DEF",
"class": "7",
"section": "B",
},
{
"name": "ABC",
"class": "8",
"section": "D",
},
]
These values of name and section, i'm getting on Click of check box.
On basis of these value , i want to filter this given array allResponse .
Values can be multiple like:
Filter the array where name is ABC and section is A and D,
Like after getting value i tried to create an object to filter like given below to filter iteratively. But not able to do it
var filterLiterals= [{"name": "ABC"},{"section": "A"},{"section": "D"}];
or
var filterLiterals= ["ABC","A","D"];
So result should be
{
"name": "ABC",
"class": "8",
"section": "A",
},
I'm confused which approach should follow to get the result.
I tried it by using || and && operator but not able to get the result what i want.
Could anybody please suggest me to suitable and proper approach to filter this array. I'm not able to do it.
Is it possible to filter in this way in javascript in any way...?
You can create a function which will accept the name and an array of section. Inside the function use filter and in the call back function return those object whose name matches and the section is included in the array of section passed to the function
var allResponse = [{
"name": "ABC",
"class": "8",
"section": "A",
},
{
"name": "DEF",
"class": "7",
"section": "B",
},
{
"name": "ABC",
"class": "8",
"section": "D",
}
]
function filterArray(name, sectionArray) {
return allResponse.filter(function(elem) {
return elem.name = name && sectionArray.includes(elem.section)
})
};
console.log(filterArray('ABC', ['A', 'D']))
If I'm reading your question correctly you want to filter your data based on what you clicked.
var allResponse = [
{
"name": "ABC",
"class": "8",
"section": "A",
},
{
"name": "DEF",
"class": "7",
"section": "B",
},
{
"name": "ABC",
"class": "8",
"section": "D",
},
];
var clickedValue = "ABC";
var filteredResponse = allResponse.filter( function(response) {
return response.name === clickedValue
});
console.log(filteredResponse);
I think this should resolve your filtering problem.
In my understanding, I need to find elements satisfying below,
name: ABC
section: A or D
var allResponse = [
{
"name": "ABC",
"class": "8",
"section": "A",
},
{
"name": "DEF",
"class": "7",
"section": "B",
},
{
"name": "ABC",
"class": "8",
"section": "D",
},
];
var filterLiterals = [
{"name": "ABC"},
{"section": "A"},
{"section": "D"}
];
const parsed = filterLiterals.reduce((acc, obj) => {
const key = Object.keys(obj)[0];
if (typeof acc[key] === 'undefined')
acc[key] = [obj[key]];
else
acc[key].push(obj[key]);
return acc;
}, {});
//console.log("parsed: ", parsed);
var answer = allResponse.filter(obj => {
let flag = true;
for (const key of Object.keys(parsed)) {
if (!parsed[key].includes(obj[key])) {
flag = false;
break;
}
}
return flag;
});
console.log(answer);
Run this!
This is a nested json file and I am trying to arrange it in a readable format to display in a table
I tried to manually put all the keys and values with in a for loop but there should be an elegant way to achieve this and hence I am reaching SO.
The actual JSON is quite a nested one and needed time to execute data with 500k rows
The result should be enhanced JSON with parent values appearing for child values as well
var property = {
"data": [{
"ID": "123456",
"name": "Coleridge st",
"criteria": [
{
"type": "type1",
"name": "name1",
"value": "7",
"properties": []
},
{
"type": "type2",
"name": "name2",
"value": "6",
"properties": [
{
"type": "MAX",
"name": "one",
"value": "100"
}, {
"type": "MIN",
"name": "five",
"value": "5"
}
]
},
{
"type": "type3",
"name": "name3",
"value": "5",
"properties": [{
"type": "MAX1",
"name": "one6",
"value": "1006"
}, {
"type": "MIN2",
"name": "five6",
"value": "56"
}]
}
]
},
{
"ID": "456789",
"name": "New Jersy",
"criteria": [
{
"type": "type4",
"name": "name4",
"value": "6",
"properties": [{
"type": "MAX12",
"name": "one12",
"value": "10012"
}, {
"type": "MIN23",
"name": "five12",
"value": "532"
}]
}
]
}]
};
var output = [];
property.data.forEach(function (users) {
var multirows = {
id: users.ID,
name: users.name,
};
for (var i = 0; i < users.criteria.length; i++) {
var criterias = {
type: users.criteria[i].type,
name: users.criteria[i].name,
value: users.criteria[i].value,
}
var mat_contacts_rows;
if (!isEmpty(users.criteria[i].properties)) {
for (var j = 0; j < users.criteria[i].properties.length; j++) {
var property = {
type: users.criteria[i].properties[j].type,
name: users.criteria[i].properties[j].name,
value: users.criteria[i].properties[j].value
};
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
} else {
var property = [];
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
}
});
console.log(JSON.stringify(output, undefined, 2))
function isEmpty(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key))
return false;
}
return true;
}
I think this could be a great exercise to you to don't answer your question but to give you some tips. You should first look at : Lodash wish has a bunch of usefull method to help you doing what you'r trying to do.
In a second time you should avoir using .forEach or for loops and try using Array.prototype.map or Array.prototype.reduce
This is my data object
{
"teachers":{
"0":{
"info":{
"id":"1",
"age":"22",
"driverlicense":"yes"
}
},
"1":{
"info":{
"id":"2",
"age":"51",
"driverlicense":"yes"
}
},
"2":{
"info":{
"id":"1",
"age":"25",
"driverlicense":"no"
}
}
}
}
What I try to read is the info object, and take the information from there.
My code
$.each(data.teachers, function(item) {
if(item.info.age < '25'){
// stores in array
yTeachers[item.info.id] = item.info.age;
}
});
But it gives me undefined back.
Is it possible to read the array teachers if the $.each is done? Sometimes it is still running when I run another function. Maybe use something like promise?
This should work for you to store ages > 25 on yTeachers as an object.
var json = {
"teachers": {
"0": {
"info": {
"id": "1",
"age": "22",
"driverlicense": "yes"
}
},
"1": {
"info": {
"id": "2",
"age": "51",
"driverlicense": "yes"
}
},
"2": {
"info": {
"id": "1",
"age": "25",
"driverlicense": "no"
}
}
}
};
var yTeachers = [];
$.each(json.teachers, function(index,item) {
var id = item.info.id;
var age = item.info.age;
if(age < 25){
// push it in array
yTeachers.push({id:age});
}
});
console.log(yTeachers);
Use this for reference check fiddle:
var data = {
"teachers": {
"0": {
"info": {
"id": "1",
"age": "22",
"driverlicense": "yes"
}
},
"1": {
"info": {
"id": "2",
"age": "51",
"driverlicense": "yes"
}
},
"2": {
"info": {
"id": "1",
"age": "25",
"driverlicense": "no"
}
}
}
};
var yTeachers=[];
$.each(data.teachers, function (i, item) {
if (item.info.age < 25) {
yTeachers[item.info.id] = item.info.age;
}
});
wait $.each is done
No need to wait for $.each to be done just call your variable after.
$.each's callback has 2 arguments, 1st for item index/key and 2nd for item value.
with arrays to check last item called and done use index == array.length -1
$.each(array, function(index, value){
if(index == array.length -1){
console("$.each is done and last item called");
}
});
with objects to check last key called and done use key == Object.keys(obj).pop() and this is your case.
$.each(obj, function(key, value){
if(key == Object.keys(obj).pop()){
console("$.each is done and last item called");
}
});
var data = {
"teachers": {
"0": {
"info": {
"id": "1",
"age": "22",
"driverlicense": "yes"
}
},
"1": {
"info": {
"id": "2",
"age": "51",
"driverlicense": "yes"
}
},
"2": {
"info": {
"id": "1",
"age": "25",
"driverlicense": "no"
}
}
}
}
$.each(data.teachers, function(i, item) {
if (item.info.age < 25) {
alert(item.info.age);
}
if (i == Object.keys(data.teachers).pop()) {
console.log("Done")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have an object which comprises of a menu.
I want to enter a category ID and get the category name, then move backwards to find it's parents. That's not easy within an object so I'm thinking to catch the parents along the way instead.
The problem I have is how to reset the parents when the end child is not found and there's nowhere else to go.
This is what I'm trying:
var data = [
{
"tree_id": "10",
"name": "babies & children",
"parent": null,
"position": "1"
}, {
"tree_id": "2",
"name": "clothing",
"parent": null,
"position": "1",
"children": [{
"tree_id": "15",
"name": "kids",
"parent": "2",
"position": "3",
"children": [{
"tree_id": "78",
"name": "fourToTen",
"parent": "15",
"position": "3",
"children": [{
"tree_id": "102",
"name": "fourToSix",
"parent": "78",
"position": "3"
}]
}]
}]
}, {
"tree_id": "55",
"name": "toys",
"parent": null,
"position": "1",
"children": [{
"tree_id": "35",
"name": "lego",
"parent": "55",
"position": "3"
}]
}
];
var crumbs = [];
function getParts(data, elem) {
for(var i = 0; i < data.length; i++) {
var obj = data[i];
if(obj.children !== undefined){
/* push parent into crumbs */
crumbs.push(obj.name);
if(obj.children[0].tree_id === elem){
/* if we've found what we're looking, we're done */
crumbs.push(obj.children[0].name);
console.log(crumbs);
} else {
/* reset parents */
crumbs = []; /* <-- this is wrong here */
/* not found, keep recursing */
getParts(obj.children, elem);
}
}
}
}
/* I want this to return
[
"clothing",
"kids",
"fourToTen",
"fourToSix"
]
but it returns
[
"fourToTen",
"fourToSix"
]
*/
getParts(data, '102');
The question is, how can I save the parents array until I'm at the end of the line and the child is not found, and reset it then?
Here's a fiddle if that's your preferred playround
Assuming category id = tree_id and category_name = name
You'll need to treat your data object like a tree, then transverse it and track the parents along the way. If something is found then dump the information you need.
So data is basically an array of objects you will be transversing.
Example:
"use strict";
var data = [
{
"tree_id": "10",
"name": "babies & children",
"parent": null,
"position": "1"
},
{
"tree_id": "2",
"name": "clothing",
"parent": null,
"position": "1",
"children": [{
"tree_id": "15",
"name": "kids",
"parent": "2",
"position": "3",
"children": [{
"tree_id": "78",
"name": "fourToTen",
"parent": "15",
"position": "3",
"children": [{
"tree_id": "102",
"name": "fourToSix",
"parent": "78",
"position": "3"
}]
}]
}]
},
{
"tree_id": "55",
"name": "toys",
"parent": null,
"position": "1",
"children": [{
"tree_id": "35",
"name": "lego",
"parent": "55",
"position": "3"
}]
}
];
// Solution
function transverse(root, tree, targetId) {
tree.push({
catId : root.tree_id,
catName : root.name
});
/* this if() must come first otherwise fails if you want to stop before end */
if (root.tree_id === targetId) {
console.log("Found id:" + targetId+ ", name=" + root.name);
console.log("Dumping parent info => " + JSON.stringify(tree));
return tree;
}
if (root.hasOwnProperty("children") && root.children instanceof Array)
root.children.forEach(child => {
transverse(child, tree, targetId);
});
}
data.forEach(item => {
transverse(item, [], /*Looking for Id=*/"102");
});
console.log("done");
Output:
Found id:102, name=fourToSix
Dumping parent info =>
[
{"catId":"2","catName":"clothing"},
{"catId":"15","catName":"kids"},
{"catId":"78","catName":"fourToTen"},
{"catId":"102","catName":"fourToSix"}]
]
Here's a compact functional way:
data = [{"tree_id":"10","name":"babies & children","parent":null,"position":"1"},{"tree_id":"2","name":"clothing","parent":null,"position":"1","children":[{"tree_id":"15","name":"kids","parent":"2","position":"3","children":[{"tree_id":"78","name":"fourToTen","parent":"15","position":"3","children":[{"tree_id":"102","name":"fourToSix","parent":"78","position":"3"}]}]}]},{"tree_id":"55","name":"toys","parent":null,"position":"1","children":[{"tree_id":"35","name":"lego","parent":"55","position":"3"}]}]
//
first = (ary, fn) => ary.reduce((r, x) => r || fn(x), false);
locate = (data, id) => _locate({children: data}, id, []);
_locate = (node, id, path) => node.tree_id === id ? path
: first(node.children || [], n => _locate(n, id, path.concat(n)));
res = locate(data, '102').map(n => n.name)
console.log(res);
I have an object type as below:
{
"1": {
"ref": "1",
"active": "1",
"showorder": "1",
"title": "Test 1"
},
"2": {
"ref": "2",
"active": "1",
"showorder": "2",
"title": "Test 2"
},
"3": {
"ref": "3",
"active": "1",
"showorder": "4",
"title": "Test 4"
},
"4": {
"ref": "4",
"active": "1",
"showorder": "9",
"title": "Test 9"
},
"5": {
"ref": "5",
"active": "1",
"showorder": "7",
"title": "Test 7"
}
}
On the basis of showorder property i need it to be arranged as follows:
{
"1": {
"ref": "1",
"active": "1",
"showorder": "1",
"title": "Test 1"
},
"2": {
"ref": "2",
"active": "1",
"showorder": "2",
"title": "Test 2"
},
"3": {
"ref": "3",
"active": "1",
"showorder": "3",
"title": "Test 3"
},
"4": {
"ref": "4",
"active": "1",
"showorder": "4",
"title": "Test 4"
},
"5": {
"ref": "5",
"active": "1",
"showorder": "5",
"title": "Test 5"
}
}
And here is my failed attempt thought i would pass the object to this function :
function reArrangeTilesObject(tilesObj){
var newObj = [];
for(var i in tilesObj){
var j = 1;
if(j == tilesObj[i].showorder){
newObj.push(tilesObj[i]);
j++;
}
}
return newObj;
}
Sorry if i am being unclear. The object is created in a random manner. So what i want is the object to be arranged as per the showorder property. so if showorder is 4 it should come in the key of 4 and not have the object of showorder 9. showorder 9 should come under the key of 9. Thanks
Steps:
Convert the object to an array (objects are unordered, arrays are ordered)
Sort the array
Code:
function reArrangeTilesObject(tilesObj) {
var tilesArray = [];
// Step 1 - convert to array
for (var i in tilesObj) {
tilesArray.push(tilesObj[i]);
}
// Step 2 - sort
tilesArray.sort(function(a, b) {
return a.showorder - b.showorder;
});
return tilesArray;
}
Result – an ordered array:
[
{"ref":"1","active":"1","showorder":"1","title":"Test 1"},
{"ref":"2","active":"1","showorder":"2","title":"Test 2"},
{"ref":"3","active":"1","showorder":"4","title":"Test 4"},
{"ref":"5","active":"1","showorder":"7","title":"Test 7"},
{"ref":"4","active":"1","showorder":"9","title":"Test 9"}
]
I may have misunderstood something but :
for (var i = 0; i < tilesObj; i++)
{
tilesObj[i].showOrder = i;
tilesObj[i].title = "Test "+i;
}
or
for (var i in tilesObj)
{
tilesObj[i].showOrder = tilesObj[i].ref;
tilesObj[i].title = "Test "+tilesObj[i].ref;
}
will do the job on the example I believe.
I can't quite understand if you're trying to rename the properties in the object array, or sort them into a new array.
If you're trying to sort:
function reArrangeTilesObject(tilesObj) {
var newObj = [];
for (var i = 1; i <= tilesObj.length; i++) {
for (var j in tilesObj) {
if (i == tilesObj[j].showorder) {
newObj.push(tilesObj[j]);
break;
}
}
}
return newObj;
}
Should add them to your newObj array based on their showorder property.
Try this one (demo):
function reArrangeTilesObject(tilesObj){
var result = {};
for(var key in tilesObj){
content = result[key] = tilesObj[key];
content.showorder = key;
content.title = "Test " + key;
}
return result;
}
It will return a new object in the original format (a Dictionary).
If you want to return an Array (and deal with possible empty indexes), just change var result = {}; into var result = [];
If you are just rewriting the showorder and title values this will work
function fix(o) {
for(var n in o) {
o[n].showorder = n;
o[n].title = "Test " + n;
}
}