Javascript returns only keys but not values - javascript

The following is the data from the source file:
{
"dubbuseqchapter+block#a7a5931f68d0482eaff2b7c9f9684e47": {
"category": "chapter",
"children": [
"dubbuseqsequential+block#968513c8f0cc4249b7cfc2290ac967dc",
"dubbuseqsequential+block#f7f730a478144a74bd127f996d6dc4f5",
"dubbuseqsequential+block#91a0d5d7cd9649a3bdf057400e0a1c96",
"dubbuseqsequential+block#28b2b171b6734b13af29735796c5ad5a",
"dubbuseqsequential+block#192a150c8aab43b9bd236773ba60b414",
"dubbuseqsequential+block#26b3464dad42460ea66f9afe89770065"
],
"metadata": {
"display_name": "Introduction course orientation"
}
},
"dubbuseqchapter+block#b2451e9195c5466db8b66f53ed06c9fd": {
"category": "chapter",
"children": [
"dubbuseqsequential+block#c95826a16f71405ba58319d23d250fc4",
"dubbuseqsequential+block#fe4e3b8b7cdd4fa0b9fe9090223b7125",
"dubbuseqsequential+block#44bbdee625dc465ebe725d2126ed0662",
"dubbuseqsequential+block#8d4daba07d4443f3b2a0b2506280ee2c",
"dubbuseqsequential+block#c68d9d3ba7de45b1b0770085e4f1f286",
"dubbuseqsequential+block#ccdca5b2aca94dbdabb3a57a75adf3fa"
],
"metadata": {
"display_name": "Module closing section"
}
}
}
The following javascript brings the top key values (i.e dubbuseqchapter+block#a7a5931f68d0482eaff2b7c9f9684e47,dubbuseqchapter+block#b2451e9195c5466db8b66f53ed06c9fd )
Javascript code
var obj = JSON.parse(jContent);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var row = createRowCopy(getOutputRowMeta().size());
var idx = getInputRowMeta().size();
row[idx++] = keys[i];
// Alert (keys.length);
putRow(row);
}
However, I am unable to get the values of the keys..(i.e. Category, Children and metadata) in this example.
I have tried Objects.values() but it returns null or object object in the Alert.

keys is an array of strings, each string being a property name.
You get the value for a property name in the usual way:
object[property_name]
i.e.
var value = obj[keys[i]];

this code shows how to navigate into parsed JsonData
var obj = JSON.parse(textJson);
var keys = Object.keys(obj);
console.log(obj[keys[0]].metadata.display_name);
this will print : Introduction course orientation

Or even this way to retrieve your subProperties
var obj = JSON.parse(textJson);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++){
console.log(keys[i]);
var subKeys = Object.keys(obj[keys[i]]);
for (var j = 0; j < subKeys.length; j++) console.log(subKeys[j] + " --> " + obj[keys[i]][subKeys[j]]);
}

Related

Parsing json containing array of array gives 'undefined'

I am trying to access elements inside an array of the array in JSON but I am getting undefined.
Error - Uncaught TypeError: Cannot read property 'lsi_short_name' of undefined at line no. 9 $("#jsondata").append(
Code is shown below :
var data = '{"response":[[{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"5":{"type":"p","lsi_short_name":"E","entities":["term_Quantity"]}}], [{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"6":{"type":"p","lsi_short_name":"F","entities":["term_Quantity"]}}]]}';
var obj = JSON.parse(data);
for(i=0;i<obj.response.length;i++) {
for (j=0; j < obj.response[i].length; j++) {
$("#jsondata").append("<li onclick=jsonDetails('"+obj.response[i][j][j+1]['lsi_short_name'] +"','"+ obj.response[i][j][j+1]['entities']+"','"+ obj.response[i][j][j+1]['attributes']+"')>"+obj.response[i][j][j+1]['lsi_short_name']+"</li>");
}
$("#jsondata").append("<br>");
}
Thanks in advance.
You key order is not serial wise, that's why you should not use j+1. So you can get the exact key first using Object.keys() then access the properties: Example:
var data = '{"response":[[{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"5":{"type":"p","lsi_short_name":"E","entities":["term_Quantity"]}}], [{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"6":{"type":"p","lsi_short_name":"F","entities":["term_Quantity"]}}]]}';
//var data = '{"response": "[[{"1": {"attributes": [], "entities": [], "lsi_short_name": "a", "type": "process"}}, {"2": {"attributes": ["d"], "entities": ["c"], "lsi_short_name": "b", "type": "process"}}], [{"1": {"attributes": [], "entities": [], "lsi_short_name": "a", "type": "process"}},{"6": {"attributes": [], "entities": [], "lsi_short_name": "f", "type": "process"}}]]"}';
var obj = JSON.parse(data);
for(var i = 0; i < obj.response.length; i++) {
for (var j = 0; j < obj.response[i].length; j++) {
var key = Object.keys(obj.response[i][j])[0];
$("#jsondata").append("<li onclick=jsonDetails('" + obj.response[i][j][key]['lsi_short_name'] +"','"+ obj.response[i][j][key]['entities']+"','"+ obj.response[i][j][key]['attributes']+"')>"+obj.response[i][j][key]['lsi_short_name']+"</li>");
}
$("#jsondata").append("<br>");
}
You are trying to access the object beyond the length of the array. You also do not have any property named attributes.
You can first get the values from the object then use the index like the following way:
var data = '{"response":[[{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"5":{"type":"p","lsi_short_name":"E","entities":["term_Quantity"]}}], [{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"6":{"type":"p","lsi_short_name":"F","entities":["term_Quantity"]}}]]}';
var obj = JSON.parse(data);
for(let i=0;i<obj.response.length;i++){
for (let j=0; j < obj.response[i].length; j++) {
let o = Object.values(obj.response[i][j])[0];
$("#jsondata").append("<li onclick=jsonDetails('"+o['lsi_short_name'] +"','"+ o['entities'][0]+"')>"+o['lsi_short_name']+"</li>");
}
$("#jsondata").append("<br>");
}
function jsonDetails(sn, en){
console.log(sn + '::' + en)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="jsondata"></div>
Your for loop should look like below:
var obj = JSON.parse(data);
for(i=0;i<obj.response.length;i++){
var x = obj.response[i];
for (j=0; j < x.length; j++) {
//Assuming the keys are serial else you need to get all the keys using Object.keys method.
var keyName = (j+1).toString();
//Access various prop of your json like this --> x[j][keyName]["lsi_short_name"]
}
}

Count and loop through JSON object of arrays

I get issues when I want to loop through a JSON array of objects.
Issues such as:
It only counts two (I assume because of they Object.keys) and I have two keys.
Loops with only one value
My code:
var codes = require('./nl.json');
for (var i = 0, l = Object.keys(codes).length; i <= l; i++) {
console.log(l) ;
var areaCodeTest = codes.netherlands[i].areaCode;
var areaNameTest = codes.netherlands[i].areaName;
it("Search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
browser.sleep(1000);
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
My Json (Short example):
{
"netherlands": [
{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
I have looked at answers such as :
Size of Object and
Length of Json
I have tried:
(var i = 0, l = Object.keys(codes).length; i <= l; i++)
(var i = 0, l = Object.keys(codes.netherlands[0]).length; i <= l; i++)
for (var i = 0, l = codes.netherlands.length; i <= l; i++) // uses last areaCode in json file and only loop with that number. It does not start from top.
Image:
some of my outputs
Expected:
What I want is to count amount of ofjects in JSON (Not the key/values)
Loop through all data and assign them to var areaCodeTest = codes.netherlands[i].areaCode; and var areaNameTest = codes.netherlands[i].areaName;
I got it to work by using the following:
var codes = require('./nl.json');
codes.forEach((item) => {
var areaCodeTest = item.areaCode;
var areaNameTest = item.areaName;
it("and search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
I am not a 100% what the => means near the foreach but I am currently researching why my code works. If you know please post a comment so that other developers also learn.
This let me think of the meme "not sure why code does not work / Not sure why code works"
You need to access the actual key in your loop in order to access codes[key]
Simplified version of your for() loop with stored variable for the object keys or using for in loop
const keys = Object.keys(codes)
for (let i = 0; i < keys.length; i++) {
// current object key and value of that property in main object
const key = keys[i], arr = codes[key];
console.log(`key = ${key}, length= ${arr.length}`)
// do another loop here for `arr` if needed
}
// OR using `for in`
for (let key in codes) {
console.log(`key = ${key}, length= ${codes[key].length}`)
}
<script>
const codes = {
"netherlands": [{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
</script>
Try this I give you a sample
const object1 = {
a: 'somestring',
b: 42,
c: false
};
var length = (Object.keys(object1).length);
Please Refer this Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

JavaScript - converting object key value pairs to JSON

I have a javascript object with 6 key value pairs:
My_Type_1:"Vegetable"
My_Type_2:"Fruit"
My_Type_3:"Dessert"
My_Value_1: "Carrot"
My_Value_2: "Apple"
My_Value_3: "Cake"
I want to construct JSON out of the above object such that it generates the following:
[{"Vegetable":"Carrot"},{"Fruit":"Apple"},{"Dessert":"Cake"}]
EDIT:
for (j=0;j<3;j++)
{
var tvArray = new Array();
var sType = 'My_Type_'+j+1;
var sValue = 'My_Value_'+j+1;
tvArray['Type'] = JSObject[sType];
tvArray['Value'] = JSObject[sValue];
}
The json.stringify doesn't produce the desired output as listed above.
How do I do this?
Thanks
You need to put parenthesis around j + 1. What you have now gives you 'My_Type_01' and so on.
var obj = {
My_Type_1:"Vegetable",
My_Type_2:"Fruit",
My_Type_3:"Dessert",
My_Value_1: "Carrot",
My_Value_2: "Apple",
My_Value_3: "Cake"
};
var pairs = [], pair;
for(var j = 0; j < 3; j++) {
pair = {};
pairs.push(pair);
pair[obj['My_Type_' + (j+1)]] = obj['My_Value_' + (j+1)];
}
console.log(JSON.stringify(pairs));

get values in pairs from json array

Firstly, this is my json value i am getting from a php source:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.
I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.
I tried this:
for (var i = 0; i < L; i++) {
var obj = res[i];
for (var j in obj) {
alert(j);
}
but all this did was to return the key name, which again did not work on being used.
So, you have an array of key/value pairs. Loop the array, at each index, log each pair:
var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];
for (var i = 0; i < obj.length; i++) {
console.log("PAIR " + i + ": " + obj[i].oid);
console.log("PAIR " + i + ": " + obj[i].cid);
}
Demo: http://jsfiddle.net/sTSX2/
This is an array that you have //lets call it a:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
To get first element :
a[0] // this will give you first object i.e {"oid":"2","cid":"107"}
a[0]["oid"] // this will give you the value of the first object with the key "oid" i.e 2
and so on ...
Hope that helps.
`
Basically what you need is grouping of objects in the array with a property. Here I am giving two functions using which you can do this
// To map a property with other property in each object.
function mapProperties(array, property1, property2) {
var mapping = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
mapping[item[property1]] = mapping[item[property1]] || [];
mapping[item[property1]].push(item[property2]);
}
return mapping;
}
// To index the items based on one property.
function indexWithProperty(array, property) {
var indexing = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
indexing[item[property]] = indexing[item[property]] || [];
indexing[item[property]].push(item);
}
return indexing;
}
var data = [{
"oid": "2",
"cid": "107"
}, {
"oid": "4",
"cid": "98"
}, {
"oid": "4",
"cid": "99"
}];
var oidCidMapping = mapProperties(data, "oid", "cid");
console.log(oidCidMapping["2"]); // array of cids with oid "2"
var indexedByProperty = indexWithProperty(data, "oid");
console.log(indexedByProperty["4"]); // array of objects with cid "4"
May not be the exact solution you need, but I hope I am giving you the direction in which you have to proceed.
If you are willing to use other library you can achieve the same with underscorejs

loop a JS Object

I have this JS object:
{
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
}
how can I loop through these items to get comment value ("comment":"text")?
You don't really need to loop to get it. Just do...
var obj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
var text = obj.data.nid[0].comment;
Or if there are several, you can use forEach...
obj.data.nid.forEach(function(val,i) {
alert( val.comment );
});
Or a traditional for loop...
for( var i = 0; i < obj.data.nid.length; i++ ) {
alert( obj.data.nid[i].comment );
}
Or if you want to build an Array, use map...
var arr = obj.data.nid.map(function(val,i) {
return val.comment;
});
Or again a traditional for loop...
var arr = []
for( var i = 0; i < obj.data.nid.length; i++ ) {
arr.push( obj.data.nid[i].comment );
}
Given:
var obj = {
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
};
The direct way to retrieve the comment is:
obj["data"]["nid"][0]["comment"]
// or
obj.data.nid[0].comment
As far as "looping" through the items to get the value, I'm not sure how a loop makes sense. Are you saying you might not know the structure of the object but you know it will have a "comment" field in there somewhere?
The "nid" array only has one item in it - if this was just a sample but really you'll have an array with more values you can loop through that array:
var nid = obj["data"]["nid"], // get a direct reference to the array to save
i; // repeating obj.data.nid everywhere
for (i=0; i < nid.length; i++) {
// do something with the comment in the current item
console.log(nid[i]["comment"]);
}
If you're just referring to that specific object (or if every object you are working with follows that same pattern), then you can just access the value directly:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
alert(theObj.data.nid[0].comment);
If you want to do something iterative, then perhaps try this:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
for (var index = 0; index < theObj.data.nid.length; index++) {
var item = theObj.data.nid[index];
if (item.comment) {
alert(item.comment);
}
}
Or if you really want to do the entire thing iteratively:
window.searchObj = function(theObj) {
if (theObj.comment) {
alert(theObj.comment);
}
if (theObj instanceof Array) {
searchArray (theObj);
}
else if (theObj instanceof Object) {
for (var key in theObj) {
searchObj(theObj[key]);
}
}
};
window.searchArray = function(theArray) {
for (var index = 0; index < theArray.length; index++) {
var item = theArray[index];
searchObj(item);
}
};
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
searchObj(theObj);

Categories

Resources