I have a problem with creating list with objects in JavaScript: the object is going to contain an Integer value and an array.
The structure will look like this (this code works):
var list = [ {
id : 1234,
dependencyList : [ {
id : 2142
}, {
id : 5313
} ]
}, {
id : 4312,
dependencyList : [ {
id : 2142
}, {
id : 5313
} ]
} ];
The problem is that I want to create this list dynamically, in other words something like this:
var list = [];
var object;
object.id=1234;
object.dependencyList = [];
object.dependencyList.push(2222);
list.push(object);
This code does not work when I try to alert(list[0].length) and it returns 0 and after using JSON.stringify(list) it only returns [[]].
Anyone know a solution for this?
list[0] is an object and not an array, which is why you're not seeing anything for length. Try:
console.log(Object.keys(list[0]).length);
Or you could even just console.log(list[0]) and check your console to ensure that it contains something.
Also, I assume you meant:
var object = {};
Because otherwise object is undefined and your script won't work. Another thing you will have to change is:
object.dependencyList.push(2222);
to:
object.dependencyList.push({id: 2222});
Object isn't defined. Do:
var object = {};
You should do list[0].dependencyList.length) also you shoud change:
object.dependencyList.push(2222);
for
object.dependencyList.push({id: 2222});
Objects are your friend.
If you need to create a lot of these things, you should probably define how they are shaped in a function. An advantage of this is that you can then create a setter for adding a dependency that hides the implementation as a push against a particular member variable.
Something like this:
function createObject( id ) {
var object = {};
object.id = id;
return object;
}
function createObjectWithDependencies( id ) {
var object = createObject( id );
object.dependencyList = [];
object.addDependency = function( dependentObject ) {
object.dependencyList.push( dependentObject );
}
return object;
}
var list = [];
var object = createObjectWithDependencies( 1234 );
object.addDependency( createObject( 2142 ) );
object.addDependency( createObject( 5313 ) );
list.push( object );
var object = createObjectWithDependencies( 4312 );
object.addDependency( createObject( 2142 ) );
object.addDependency( createObject( 5313 ) );
list.push( object );
console.log( list );
Related
I have the following javascript
{
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"
[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1},
{\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
What I am trying to do is, to use javascript to get the TagName from Tags section
When i use JSON.parse(Obj.Tags); I get everything under Tags section where i only want TagName
Is it possible?
It's possible. You can use the .map function.
var tagNames = obj.Tags.map(function(x){
return x.TagName;
});
var obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":
[{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}]
};
var tagNames = obj.Tags.map(function(x){
return x.TagName;
})
console.log(tagNames)
I think I probably get what your question is.
Would you like your Tags to be only array of TagName?
Here's example code:
var Obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
// Get Tags data to array object
var Tags = JSON.parse(Obj.Tags);
// Get simple array of TagNames
var TagNames = Tags.map(x=>x.TagName);
console.log(TagNames);
// Get array of objects with only TagName key value pair
var TagNamesFormat2 = Tags.map(function(x){
return {"TagName" : x.TagName}
});
console.log(TagNamesFormat2);
You can use map() on Tags
// Parsed object
var data = {
"Exists": true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,
"Fav":false,
"Shield":false,
"Tags": [
{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}
]
}
console.log(data.Tags.map(tag => tag.TagName));
Try tags.map(a => a.TagName);
var myObj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
};
var tags = JSON.parse(myObj.Tags);
var tagNames = tags.map(a => a.TagName);
console.log(tagNames);
I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);
I am trying to store an array inside and object like this:
var fieldData = {
checkedItem: {
fieldID : “1234”,
SelectedFields : []
}
checkedItem: {
fieldID : “12345”,
SelectedFields : []
}
}
I then want to also replace all selected fields to this object at a later stage.
I am a newbie to this so not sure how it would be done, I have tried everything I can think of!
The later changes to the object will referenced by fieldID.
I have tried stuff like:
fieldData["fieldID"] = selectedFieldSeq;
fieldData[selectedFieldSeq]["SelectedFields"] = $('#Tree').jqxTree('getCheckedItems');
$('#Tree').jqxTree('getCheckedItems');
returns an array of checked items on my tree.
This should do it:
'fieldID = $('#Tree').jqxTree('getCheckedItems');'
'fieldData.SelectedFields = fieldID'
There is a problem with this line :
fieldData[selectedFieldSeq]["SelectedFields"]
fieldData[selectedFieldSeq] is not defined, so it's return undefined
You need to initialize it before using it :
if (!fieldData[selectedFieldSeq]) {
fieldData[selectedFieldSeq] = {
SelectedFields : []
};
}
After, you can assign some value to SelectedFields.
Or did you want to simply do this : fieldData.SelectedFields = ...; ?
I have created a multidimensional array for a jobs feed like so:
var jobs = [
["JOB222" , "Painter"],
["JOB333" , "Teacher"],
["JOB444" , "Delivery Driver"],
];
I can access the array using the index number
alert( jobs[2][1] ); // Alerts Delivery Driver
If I set the reference number manually, I can loop through the array to find a match.
var viewingJobRef = "JOB333";
for (var i=0;i<jobs.length;i++) {
if (jobs[i][0] == viewingJobRef) {
alert(jobs[i][1]); // This will alert Teacher
}
}
So my question is, is it possible to access the array directly and not use a loop?
var viewingJobRef = "JOB333";
alert( jobs[viewingJobRef][1] ); // I want this to alert Teacher
Firefox error console says:
jobs[viewingJobRef]is undefined, how do I do it?
You want to use objects:
var jobs = {
"JOB222" : "Painter",
"JOB333" : "Teacher",
"JOB444" : "Delivery Driver"
};
Access like this :
var viewingJobRef = "JOB333";
alert( jobs[viewingJobRef] );
OR
alert( jobs["JOB333"] );
OR
alert( jobs.JOB333 );
You may use objects:
var jobs = {
"JOB222": "Painter",
"JOB333": "Teacher",
"JOB444": "Delivery Driver"
};
And loop with:
for ( var i in jobs ) {...}
Or access directly like:
alert( jobs.JOB333 );
How to I fetch some rows of particular pattern ?
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
Here I want a map with key starting with kk_list
I tried some thing like this, which obviously didnt work.
console.log(list["kk_list_\w+"])
You can try something like this:
function filterArray( list, regex )
{
var outputArray = {};
for( var key in list )
{
if( key.match( regex ) )
{
outputArray[key] = list[key];
}
}
return outputArray;
}
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
console.log( filterArray( list, /kk_list_\w+/ ) );
It uses a function to filter the array and make a new one with the regex-selected keys.
You can reduce the object to one with just the keys matching a specified regex using the following:
Object.prototype.reduce = function(regex) {
var newObj = {}, x;
for(x in this) if(this.hasOwnProperty(x) && (!regex || regex.test(x))) newObj[x] = this[x];
return newObj;
};
And then call it as list.reduce(/_first.*$/) => Object {kk_first_name: "Reck", kk_first_no: "5555"}
You can use the following code:
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
var line=JSON.stringify(list);
var ar=line.match(/(kk_list[^" :]*)/g)
ar.forEach(function(val){
console.log(eval("list."+val));
});
OUTPUT
jack
123