JSON.parse(data) return [undefine] - javascript

data = {
"users": [
[{
"value": "01",
"text": "ABC XYZ"
}],
[{
"value": "02",
"text": "XYZ ABC"
}]
]
}
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.users.length; i++) {
var userlist = jsonData.users[i];
alert(userlist.text)
}
This output: [undefine];
But i want to get [ABC XYZ] and [XYZ ABC].
So how can I get text or value from this array?

data is already a JavaScript object, so no need for the extra JSON.parse.
You are getting an undefined result because users is an array of arrays, rather than an array of objects.
Try accessing the userlist like this:
var userlist = data.users[0][i];
JSBin: https://jsbin.com/sifoyivayi/edit?html,js,output

Your object contains nested array. Try like following.
var data = { "users": [[{ "value": "01", "text": "ABC XYZ" }], [{ "value": "02", "text": "XYZ ABC" }]] };
for (var i = 0; i < data.users.length; i++) {
var userlist = data.users[i][0];
alert(userlist.text);
}

Try like this:
var data={"users":[[{"value":"01","text":"ABC XYZ"}],[{"value":"02","text":"XYZ ABC"}]]};
for (var i = 0; i < data.users.length; i++) {
var userlist = data.users[0][i];
alert(userlist.text);
}

Related

How to convert array to object?

I have a array different objects
{
prac:[{
"name":"xxx",
"id":"1"
}],
abc: [{
"description":"this is test description",
"status":"active"
}]
}
Here I want to convert prac array to object.
You should take the first element of the array. That's it
var obj = {
prac: [{
"name": "xxx",
"id": "1"
}],
abc: [{
"description": "this is test description",
"status": "active"
}]
};
obj.prac = obj.prac[0];
console.log(obj);
Try this :
var jsonObj = {
prac:[{
"name":"xxx",
"id":"1"
}],
abc: [{
"description":"this is test description",
"status":"active"
}]
};
var arrObj = jsonObj.prac;
function toObject(arr) {
var newJson = {};
for (var i = 0; i < arr.length; ++i)
newJson[i] = arr[i];
return newJson;
}
console.log(toObject(arrObj));

Converting list of classes with full names within HTML to JSON

I have an ASP.NET MVC 4 application where a list of classes, with their full namespaces, are bound to a listbox. This generates HTML as follows:
<select id="myclasses">
<option>Api.Domain.Interfaces.MyClass1</option>
<option>Api.Domain.Interfaces.MyClass2</option>
<option>Api.Domain.Interfaces.MyClass3</option>
<option>Api.Domain.Models.MyModel1</option>
<option>Api.Domain.Models.MyModel2</option>
<option>Api.Infrastructure.Repositories.MyRepo1</option>
<option>Api.Infrastructure.Repositories.MyRepo2</option>
</select>
I would like to use JavaScript/jQuery to generate a JSON representation of this HTML stored in a variable as follows:
var classes =
[{ "text": "Api", "children":
[{ "text": "Domain", "children":
[{ "text": "Interfaces", "children":
[{ "text": "MyClass1" }, { "text": "MyClass2" }, { "text": "MyClass3" }]
},
{ "text": "Models", "children":
[{ "text": "MyModel1" }, { "text": "MyModel2" }]
}]
},
{ "text": "Infrastructure", "children":
[{ "text": "Repositories", "children":
[{ "text": "MyRepo1" }, { "text": "MyRepo2" }]
}]
}]
}];
The fully qualified class names are already in a tree-like structure, so I would imagine that there should be a fairly easy way to achieve what I'm trying to do. Should I be getting the inner HTML of the element using $("#myclasses").html() and then performing string manipulations, or is there a simpler way?
Here is a try with Jquery, though you'll have an empty list of children for the last element. Could be modified if that's a problem.
I added multi selection also to give a shot.
http://jsfiddle.net/c8e7kkhh/1/
$(function() {
$("#button").click(function(){
var output = [];
var input = $( "#myclasses option:selected" );
for (var i = 0; i < input.length; i++) {
var chain = input[i].text.split(".");
var currentNode = output;
for (var j = 0; j < chain.length; j++) {
var wantedNode = chain[j];
var lastNode = currentNode;
for (var k = 0; k < currentNode.length; k++) {
if (currentNode[k].text == wantedNode) {
currentNode = currentNode[k].children;
break;
}
}
// If we couldn't find an item in this list of children
// that has the right name, create one:
if (lastNode == currentNode) {
var newNode = currentNode[k] = {text: wantedNode, children:[]};
currentNode = newNode.children;
}
}
}
$("#result").html(JSON.stringify(output));
});
});

Compare two objects in jQuery and get the difference [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 7 years ago.
Using jQuery I would like to compare 2 objects:
sourceArray:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
destination array
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
What I would like to do, is compare the target object with the source object based on the ID and find the mis-matched entries with a description on the resultant object. So the result will look like this:
var resultArray = [{
"Name": "Double",
"URL": "yyy",
"ID": 888,
"desc": "missing in source"
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345,
"desc": "missing in destination"
}];
Any quick help is really appreciated.
This isn't a good use of jQuery, but here is some vanilla javascript that does what you want.
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
https://jsfiddle.net/9gaxsLbz/1/
If you are wanting to dedupe your array, this will work:
var merged = origArray.concat(destArray);
var unique = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? false : this.push(item.ID);
}, []);
Fiddle: https://jsfiddle.net/Ljzor9c6/
If you are only wanting items that were duped, you can easily invert the condition:
var merged = origArray.concat(destArray);
var dupes = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? true : !this.push(item.ID);
}, []);
You can loop through the items in the first array and put the ID's in a map, then loop through the items in the second array and remove the matching ID's and add the missing.
Then just loop through the map to create the objects in the resulting array:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var map = {};
for (var i = 0; i < origArray.length; i++) {
map[origArray[i].ID] = 'source';
}
for (var i = 0; i < destArray.length; i++) {
var id = destArray[i].ID;
if (id in map) {
delete map[id];
} else {
map[id] = 'destination';
}
}
var resultArray = [];
for (key in map) {
var arr = map[key] == 'source' ? origArray : destArray;
for (var i = 0; arr[i].ID != key; i++) ;
resultArray.push({
Name: arr[i].Name,
URL: arr[i].URL,
ID: arr[i].ID,
desc: 'missing in ' + map[key]
});
}
// show result in StackOverflow snippet
document.write(JSON.stringify(resultArray));
var result = [];
for(var i = 0; i < oa.length; i++) {
var idx = mIndexOf(oa[i].ID);
if(idx > -1) {
oa.splice(i, 1);
da.splice(idx, 1);
}
}
for(var i = 0; i < oa.length; i++) {
var ln = result.length;
result[ln] = oa[i];
result[ln].desc = "missing in destination";
}
for(var i = 0; i < da.length; i++) {
var ln = result.length;
result[ln] = da[i];
result[ln].desc = "missing in origin";
}
function mIndexOf(id) {
for(var i = 0; i < oa.length; i++)
if(oa[i].ID == id)
return i;
return -1;
}
console.log(result);
0: Object
ID: 345
Name: "Double"
URL: "yyy"
desc: "missing in destination"
1: Object
ID: 888
Name: "Double"
URL: "yyy"
desc: "missing in origin"
jsfiddle DEMO
For things like this, you should use lodash. With lodash you can just do this:
var resultArray = _.defaults(destArray, origArray);

How to add a node to a child object

I want to insert an object say-{id:parentid+appendvalue} in each of children array using javascript/jquery. Here is my sample data:
var obj={
"name": "root",
"id":12,
"children": [
{
"name": "child-1",
"children": [
{
"name": "inner-child"
}
]
},
{
"name": "child-2"
}
]
};
Each object is of the format {name,id,children[]}.Here , I want to insert {id:parentid+".0"} recursively to all children nodes so that , I would get the following output.
var obj={
"name": "root",
**"id":12**,
"children": [
{
"name": "child-1",
**"id": 12.0**
"children": [
{
"name": "inner-child",
**"id" : 12.0.0**
}
]
},
{
"name": "child-2",
**"id": 12.1**
}
]
};
Please note the children object is not restricted to any level. Please help.
You could try something like this:
for(var i = 0; i < obj.children.length; i++)
{
var parentIDString = parentid + ".0";
for(var j = 0; j < i; j++)
{
parentIDString += ".0";
}
obj.children[i]['id'] = parentIDString;
}

How to convert from a JSON array to a JSON object

I have this JSON that I'm getting back from a web service call:
{
"name": "My Name",
"path": "my path",
"id": "44",
"type": "my type",
"classes": "my classes"
},
{
"name": "his Name",
"path": "his path",
"id": "76",
"type": "his type",
"classes": "his classes"
}
I then need to convert it to this format
{
"44" : { "name" : "My Name", "path" : "my path" },
"76" : { "name" : "his Name", "path" : "his path" }
}
My initial naive attempt was this:
var myData = [];
for (var i = 0; i < rawData.length; i++) {
myData.push({
rawData[i].id :
{
"path": rawData[i].path,
"name": rawData[i].name
}
});
which fails with syntax errors, so I eventually got to this:
var myData = [];
for (var i = 0; i < rawData.length; i++) {
myData.push(rawData[i].id,
{
"path": rawData[i].path,
"name": rawData[i].name
});
and it mostly works. My array is populated, but the problem is that my myData array doesn't have the "44", and "76" part of the object, just the { "name" : "", "path" : "" } part. I expect this is due to a lack of understanding on my part of how JSON and javscript objects work.
Your desired output isn't an array, so that's your starting point. The output you've said you want is an object, not an array.
You build your result by creating a blank object and then adding the objects to it using id as the key:
var myData = {};
rawData.forEach(function(entry) {
myData[entry.id] = {
name: entry.name,
path: entry.path
};
});
Or if you don't want to use forEach (it's ES5, but can be shimmed for older browsers), the old-fashioned way:
var myData = {};
var index, entry;
for (index = 0; index < rawData.length; ++index) {
entry = rawData[index];
myData[entry.id] = {
name: entry.name,
path: entry.path
};
}
Don't use Array.prototype.push(), use the square bracket notation and define your output as an object not an array.
var myData = {};
for (var i = 0; i < rawData.length; i++) {
myData[rawData[i].id] = {
"path": rawData[i].path,
"name": rawData[i].name
}
}
You need to convert your id to a string?
var myData = {};
for (var i = 0; i < rawData.length; i++) {
myData[String(rawData[i].id)] = {
"path": rawData[i].path,
"name": rawData[i].name
};
}
A variation on what other posters have written:
// Create a new empty object.
var out = {};
// Loop over your array of objects
// Add the each object id as a key to the output object, and the object as the value.
for (var i = 0, l = arr.length; i <l; i++) {
var obj = arr[i];
out[obj.id] = obj;
// Delete the properties from the newly added object you don't want.
delete obj.id;
delete obj.type;
delete obj.classes;
}

Categories

Resources