How should I access the JSON Array having a numeric key? - javascript

{
"2": [{
"name": "Jeevan",
"age": "7"
},
{
"name": "Jeet",
"age": "8"
}],
"school": "Kendriya Vidyalaya"
}
I am having this JSON stored in variable named Obj. I would like to access individual JSON Objects inside of JSON Array which has a a key as "2".
Please help me to access the same.
As far as conventional way is considered i.e
Obj.key, it is not applicable here because Obj.2 or Obj."2" is not allowed.

I believe you are working with javascript.
Try to access the date like this:
array = Obj["2"]

This should work
var o = { "2": [{ "name": "Jeevan", "age": "7" }, { "name": "Jeet", "age": "8" } ], "school": "Kendriya Vidyalaya" };
o["2"];
o["school"]

Related

Insert key's value in the array of object having same key

Say I've an array of object:
const Info = [{
"id": "1aa2",
"details": [{
"name": "rusty",
"age": "12",
"favourite": [ObjectId("602b696cb783fc15845d015e"), ObjectId("602b696cb783fc15845d0112")]
}]
},
{
"id": "3aa2",
"details": [{
"name": "john",
"age": "122",
"favourite": [ObjectId("602b696cb783fc15845d0112s"), ObjectId("602b696cb783fc15845d01wqs")]
}]
}
]
I want to merge favourite in one array as:
["favourite": [
ObjectId("602b696cb783fc15845d015e"),
ObjectId("602b696cb783fc15845d0112"),
ObjectId("602b696cb783fc15845d0112s"),
ObjectId("602b696cb783fc15845d01wqs")
]
]
I tried using for loop but it's creating nasty nested for loop which is reducing performance a lot.
Basically, you need to iterate through Info collection, iterate through 'details' sub-collection, and copy all data into a new array. After, just create a new structure using favs variable content or paste this code as object value directly.
BTW your result array need's to contain an object at least, like that:
[ { favourite: [...] } ]
About nested structures, you should try https://lodash.com/docs/4.17.15#flatMapDeep (at least just check the code)
const Info = [{
"id": "1aa2",
"details": [{
"name": "rusty",
"age": "12",
"favourite": ['ObjectId("602b696cb783fc15845d015e")', 'ObjectId("602b696cb783fc15845d0112")']
}]
},
{
"id": "3aa2",
"details": [{
"name": "john",
"age": "122",
"favourite": ['ObjectId("602b696cb783fc15845d0112s")', 'ObjectId("602b696cb783fc15845d01wqs")']
}]
}
]
const favs = Info.reduce((acc, item) => {
item.details.forEach(detail => {
acc.push(...detail.favourite);
})
return acc;
}, []);
console.log(favs);

Printing object from Local Storage

I have a an expenses form which saves data to the Browser local storage. I have abutton on the page below the form so that after you fill in in the form you can then click to print out the data in a nice format.
I have to use the JSON data in the local storage due to the functionality of my app.
I am using the js variable to grab the data from local storage:
var my_expenses = localStorage.getItem('my_expenses');
Here is the entry in my browser local storage, with the unminified value.
Key:my_expenses
Value:
{
"income": {
"1": {
"name": "Pay (after tax)",
"freq": "26",
"value": "233"
},
"2": {
"name": "Partners take home pay",
"freq": "4",
"value": "10"
},
"3": {
"name": "Bonuses/overtime",
"freq": "26",
"value": "30"
},
"4": {
"name": "Income from savings and investments",
"freq": "1",
"value": "50"
},
"5": {
"name": "Child support received ",
"freq": "12",
"value": "40"
}
},
"outgoings": {
"1": {
"name": "Electricity",
"freq": "4",
"value": "0"
},
"2": {
"name": "Gas",
"freq": "4",
"value": "0"
},
"3": {
"name": "Water",
"freq": "4",
"value": "0"
},
"4": {
"name": "Internet",
"freq": "4",
"value": "0"
},
"5": {
"name": "Telephone",
"freq": "4",
"value": "0"
},
"6": {
"name": "Car Insurance",
"freq": "1",
"value": "0"
}
}
}
According to Print.js you can print JSON data like so (including my variable with my local storage data):
<button type="button" onclick="printJS({printable: my_expenses, properties: ['name', 'freq', 'value'], type: 'json'})">
Print JSON Data
For some reason I am getting an error in my console and I cant figure it out and no dialogue opens for printing.
Uncaught Error: Missing printable information.
at init (print.min.js:1)
at HTMLButtonElement.onclick ((index):156)
I think it may be the structure of my JSON in the local storage?. any help would be deeply appreciated.
Tried Using JSON.parse() like so:
var my_expenses = JSON.parse(localStorage.getItem("my_expenses"));
before I added JSON parse. I was getting the wrror and this was the output of the local storage in the console.
after I added it this was the output and the print button seemed to work:
But the print dialogue has no data?
How the object is created and the local storage functions:
//Set the default incomes and outgoings here
var defaultsObj = {
'income':{
1:{name:"Pay (after tax)",freq:52,value:0},
2:{name:"Partners take home pay",freq:4,value:0},
3:{name:"Bonuses/overtime",freq:26,value:0},
4:{name:"Income from savings and investments",freq:1,value:0},
5:{name:"Child support received ",freq:12,value:0}
},'outgoings':{
1:{name:"Electricity",freq:4,value:0},
2:{name:"Gas",freq:4,value:0},
3:{name:"Water",freq:4,value:0},
4:{name:"Internet",freq:4,value:0},
5:{name:"Telephone",freq:4,value:0},
6:{name:"Car Insurance",freq:1,value:0}
}
};
//Functions to store and retrieve objects from localstorage
function ls_store(name,o){
localStorage.setItem(name, JSON.stringify(o));
};
function ls_read(name){
return JSON.parse(localStorage.getItem(name));
};
function set_defaults(){
ls_store('my_expenses',defaultsObj);
expensesObj = ls_read('my_expenses');
}
//If our localstroage items are empty let's store the defaults
if(ls_read('my_expenses')==null){
set_defaults();
}
You dont save an array and printjs wait for an array.
Try to save into two differents array, first, to see the result into your pdf.
If data is displayed for first array you must : call two times printjs, one for first array and another for second array OR combine theses two array into a single and maybe adding an attribut to disting if is incombe or outcome.

Find object by property in JSON array

I have problem with get string in JSON data. Format as below:
[
{
"name": "Alice",
"age": "20"
},
{
"id": "David",
"last": "25"
},
{
"id": "John",
"last": "30"
}
]
Sometime it changes position together, John from 3rd place go to 2nd place:
[
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
]
If i use data[3].age to get John's age, and data change position, I will get David's age.
Is there any method I can use to find the object with name David and get the age value?
You can use array.find() method as,
var myArray = [
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
];
//Here you are passing the parameter name and getting the age
//Find will get you the first matching object
var result = myArray.find(t=>t.name ==='John').age;
console.log(result);
It's better to use array.filter() (better browser support)
myArray.filter(function(el){return el.name == "John"})[0].age

Nested json data in js -get the values from nested array

Got the output result in json nested array.
Help to access the USER-id of this json format .
var result = {
"USER": {
"id": "11456",
"email": "g#gmail.com",
"name": "g"
},
"status": "true",
"group-title": "title",
"group-name": "2-Group"
}
I thin your json structue is wrong. Below is the corrected structure
{
"status": "true",
"USER": {
"id": "11456",
"name": "g",
"email": "g#‌​gmail.com"
},
"group-name": "2-Group",
"group-title": "title"
}
The json usages in JS
var result={ "status": "true", "USER": { "id": "11456", "name": "g", "email": "g#‌​gmail.com" }, "group-name": "2-Group", "group-title": "title"};
resultJson=jQuery.parseJSON(result);
var userId=resultJson.USER.id; // here you will get the user id
Please try this way. This may help you. Don't forget to add jQuery in your script
json values are not seperated by
;
the correct formate for your json is
var result = {"status":"true","USER":{"id":"11456","name":"g","email":"g#gmail.com"},
"group-name":"2-Group","group-title":"title"}
for this formate u can assess the user id by
result.USER.id;
From your code, you can directly access Id as below:
<script>
var result = {
"USER": {
"id": "11456",
"email": "g#gmail.com",
"name": "g"
},
"status": "true",
"group-title": "title",
"group-name": "2-Group"
};
alert(result.USER.id);
</script>

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

Categories

Resources