need help recursive javascript function - json

I want to turn json string
treeNodes =[{managerid:root,Employeeid:01},
{managerid:01,Employeeid:11},
{managerid:01,Employeeid:22},
{managerid:22,Employeeid:33},
{managerid:22,Employeeid:44}];
into this json string using javascript.
json={
id:root,
children[{
id:01,
children[
{id:11},
{id:22}
]},
{
id:22,
children[
{id:33},
{id:44}
]
}
Can someone help with java script function?

I think you need something like this (I assume root is a declared variable):
var rootNode = {Employeeid:root};
var json = makeJsonNode(treeNodes, rootNode);
// Do something with "json"
// ...
function makeJsonNode(treeNodes, node){
var jsonNode = { id : node.Employeeid };
var children = [];
for(var i=0; i<treeNodes.length; i++){
if(treeNodes[i].managerid === node.Employeeid){
children.push(makeJsonNode(treeNodes, treeNodes[i]));
}
}
if (children.length > 0) jsonNode.children = children;
return jsonNode;
}

Related

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

How to get nested deep property value from JSON where key is in a variable?

I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)

Access array element by string in AS3

As we know its possible to access field by name using indexer.
var obj:* = {name:"Object 1"};
trace(obj["name"]); // "Object 1"
But how to access an array element by String?
var arr:Array = new Array();
var obj:* = {items:arr};
trace(obj["items[0]"]); // Undefined
Ok, basically you want to be able to have a string be interpreted as actionscript. No elegant solution I'm afraid. You could write a parser that handles some simple syntax in a string and retrieves the value.
Here's a simple example:
var obj:Object = {
items:[1, 2, 3],
subObj: {
subitems: [4, 5, 6]
}
};
trace(getValueInObject(obj, "items[0]")); // 1
trace(getValueInObject(obj, "subObj.subitems[2]")); // 6
// takes an object and a "path", and returns the value stored at the specified path.
// Handles dot syntax and []
function getValueInObject(obj : Object, pathToValue : String) : * {
pathToValue = pathToValue.replace(/\[/g, ".").replace(/]/g, "");
var pathFractions : Array = pathToValue.split(".");
var currentObject : Object = obj;
while (pathFractions.length > 0 && currentObject != null) {
var fraction : String = pathFractions.shift();
currentObject = currentObject[fraction];
}
if (currentObject != null) {
return currentObject;
}
return null;
}

Parsing json jquery

My request ajax with json_encode:
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"},
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]
var string = JSON.stringify(data);
var obj = $.parseJSON(string);
console.log(string);
var idHome = obj.idHome;
var photo = obj.Photo;
console.log(obj.idHome);
console.log(obj.Photo);
Problem with parsing json
console log :
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]
undefined
undefined
It is an array so you need to loop through, there are so many ways to do it.
for (i = 0; i < obj.length; i++) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
or:
obj.forEach(function(val) {
console.log(val.idHome);
console.log(val.Photo);
});
or:
for (var i in obj) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
Jquery use :
$.each(obj, function(_, val){
console.log(val.idHome);
console.log(val.Photo);
});
and so on....
Your json is an array of three objects.
Try
console.log(obj[0].idHome);
console.log(obj[0].Photo);
More info:
http://www.w3schools.com/json/json_syntax.asp

find out object item names in as3

let's say you're passing an object to a function
{title:"my title", data:"corresponding data"}
how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?
You can use a for loop as follows:
for (var key:String in obj) {
var value:String = obj[key];
trace(key + ": " + value);
}
Or use the introspection API.
The Flex 3 Help page on Performing Object Introspection has a good overview of these.
You can use a for(String in Object) loop like so:
var i:String;
for(i in object)
{
var key:String = i;
var value:Object = object[i];
// do stuff with key/value
}
PS it would make more sense obviously to use key in the loop, my example is done for the sake of demonstration.
Why was this downvoted.. Because I didn't do a function?
function findKeys(obj:Object):Array
{
var ar:Array = [];
var i:String;
for(i in obj)
{
ar.push(i);
}
return ar;
}
var ob:Object = {things:"value", other:5};
trace(findKeys(ob)); // other,things