Well I've just discovered JSON today but I have a problem using it correctly. I really can't find a solution...
Basically, I just want to count the elements of my array (count all the dM), and wrap on a specific element (dM1 for example).
Here is my code so that you can understand: http://jsfiddle.net/dRycS/9/
Adding to what #Pointy said here is your code modified:
JSFiddle Demo
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var dMContent = {
"dM1" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
},
{
"name" : "FfFfFfFf",
"link" : "http://test.com"
},
{
"name" : "GgGgGgGg",
"link" : "http://test.com"
}
],
"dM2" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
},
{
"name" : "FfFfFfFf",
"link" : "http://test.com"
}
],
"dM3" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
}
]
};
var STORAGE = JSON.stringify(dMContent);
var parsed = JSON.parse(STORAGE);
// WHAT I WANT TO DO
// Count the number of dM
console.log(Object.size(parsed)); //gives you 3
//display the content
for(var i in parsed){
console.log('data in ' + i);
for(var j=0; j<parsed[i].length; j++){
console.log(parsed[i][j].name + ' ' + parsed[i][j].link);
}
}
What you've got there is not an Array; it's an Object. Array objects do have a "length" property, but Objects do not.
It's not clear exactly what you want; if you wanted to count every property of every object inside of "dMContent", you'd write something to count recursively. For a single "layer" of an object, something like this might be what you want:
function objectSize(obj) {
var count = 0;
for (var k in obj) {
if (obj.hasOwnProperty(k)) ++count;
}
return count;
}
In your code dMContent is an Object, not an Array.
To count elements in an Object, do this:
var i = 0;
for (x in parsed) {
if (parsed.hasOwnProperty(x)) {
i++;
}
}
alert(i);
Try this:
function objectCount(obj) {
objectcount = 0;
$.each(obj, function(index, item) {
objectcount = objectcount + item.length;
});
return objectcount;
}
objectCount(obj);
where obj is a json object with json array as sub objects
Related
I want to loop only one time or I want to loop specified times in for loop.
I have very big JSON and the structure is like this:
{
"-item1" : {
"added_by" : "admin#gmail.com",
"id" : "-KlxUo5HGr7sdEsgEea1",
"name" : "Apivita"
},
"-item2" : {
"added_by" : "admin#gmail.com",
"id" : "-KlxUq4SgTfefuAB2XH1",
"name" : "Lierac"
},
"-item3" : {
"added_by" : "admin#gmail.com",
"id" : "-KlxUs1I3P7z2YDFtQPh",
"name" : "Bioderma"
}
}
How to loop only one time?
// get the object key
for(var key in data) {
var value = data[key];
}
I want only the item1 object data.
Or the first 5 items
is that easy ?
You can simply add a counter and exit the loop if the counter has reached its limit:
var counter = 0;
var limit = 3;
var data = [1, 2, 3, 4, 5, 6, 7];
for (var key in data) {
var value = data[key];
console.log('key: ' + key + ' --> value: ' + value);
if (++counter >= limit) break;
}
You can try something below to get a particular value alone.
//get item2
var value = data["-item2"]
Or if you want to take first 5 values then check below code.
// get the object key
var keyVal=1;
for(var key in data) {
if(keyVal <= 5){
var value = data[key];
}
keyVal++;
}
Just use this
var start = 0;
var end = 0;
for(var i = start; i<end; i++){
var value = data["-item"+i]
}
I have this data i have pulled from mongodb
{
"_id" : "RLvWTcsrbRXJeTqdB",
"examschoolid" : "5FF2JRddZdtTHuwkx",
"examsubjects" : [
{
"subject" : "Z4eLrwGwqG4pw4HKX"
},
{
"subject" : "fFcWby8ArpboizcT9"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examname" : "First",
"examdate" : ISODate("2016-05-07T22:41:00Z"),
"examresultsstatus" : "notreleased"
}
I want to iterate examsubjects and finally insert an object inside my array and get an array like this
"examsubjects" : [
{
"Z4eLrwGwqG4pw4HKX" : "0",
"fFcWby8ArpboizcT9" : "0"
}
],
This is my code
var result = new Array();
for (i = 0; i < doc.examsubjects.length; i++) {
var arr = {};
for (var prop in doc.examsubjects[i]) {
arr[doc.examsubjects[i][prop]] = 0;
}
result.push(arr);
}
which gives me this array
"examsubjects" : [
{
"Z4eLrwGwqG4pw4HKX" : 0
},
{
"fFcWby8ArpboizcT9" : 0
}
],
How can i get the array i want?.
In your attempt, you initialize an empty array and push a new object into it for every object in your examsubjects array, when what you want to do is put the data from all your exam subjects into just one object, when you then apparently want to be in an array. One of the many ways to accomplish that is like this:
var result = [{}];
for (i = 0; i < doc.examsubjects.length; i++) {
for (var prop in doc.examsubjects[i]) {
// Here we repeatedly modify the single
// object in our results array
result[0][doc.examsubjects[i][prop]] = 0;
}
}
// result now looks like [{"Z4eLrwGwqG4pw4HKX": "0", "fFcWby8ArpboizcT9": 0"}]
I have the following JSON:
{
"_id" : ObjectId("542e65368a1cec1227ae2bac"),
"result" : {
"full" : {
"Array1" : [
"mytext1",
"mytext2"
],
"Array2" : [
"mytext3",
"mytext3"
]
}
}
}
To get everything: OK
console.log("response ", response);
To get the _id: OK
console.log("_id ", response._id);
But I can't access to mytext1, mytext2, ...
How I can proceed with angularjs?
Thanks for your help !
response is an object. result is an object. full is an object. Array1 and Array2 are, obviously enough, arrays.
For mytext1:
response.result.full.Array1[0]
For mytext2:
response.result.full.Array1[1]
For mytext3:
response.result.full.Array2[0]
For mytext4:
response.result.full.Array2[1]
If you want to log everything in the array, use a simple for...loop:
var arr = response.result.full.Array1;
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i]);
}
var q = {
"_id" : "542e65368a1cec1227ae2bac",
"result" : {
"full" : {
"Array1" : [
"mytext1",
"mytext2"
],
"Array2" : [
"mytext3",
"mytext3"
]
}
}
};
//The next for iterates over the names Array1, Array2 (and if you have more)
for(var array in q.result.full)
{
//This for iterates over the elements of each array
for(i = 0; i < q.result.full[array].length; i++)
{
console.log(q.result.full[array][i]);
}
}
Is there a way to get the value of
{
"first": "first-string",
"second-array": [
{
"first-Obj": 2
}
]
}
is there a way to get or update the values by using a path like string
ex: to change the first-obj's value to 1000
changeTheValueAt('second-array/0/firstObj', 1000)
is there any function like above changeTheValueAt or a method.
Use the following function for that -
function changeTheValueAt(obj, path, value) {
var parts = path.split("/"),
final = obj[parts[0]],
i;
for (i = 1; i < parts.length; i++) {
if (i + 1 < parts.length) {
final = final[parts[i]];
}
else {
final[parts[i]] = value;
}
}
}
and then call it like this -
var ob = {
"first": "first-string",
"second-array": [
{
"first-Obj": 2
}
]
};
changeTheValueAt(ob, "second-array/0/first-Obj", 1000)
alert(ob["second-array"][0]["first-Obj"]);
JSFiddle Demo.
Because second-array is an array, you can't access it by name. You can access it by index or you can iterate over and find a value and change it when found.
var yourObj = {
"first": "first-string",
"second-array": [
{
"first-Obj": 2
}
]
};
yourObject.second-array[0].first-Obj = 1000;
You could do something like:
var changeFirstObj = function(node1, node2, new val){
yourObj[node1].forEach(o, i){
for(var prop in o){
if(prop == node2){
o[node2]=newVal;
}
};
changeFirstObj('second-array', 'first-Obj', 1000);
But that's not really very flexible.
I have the following array:
var = array[
{"id" : "aa", "description" : "some description"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}]
and I try to find the index of the array that contains the id === "bb". The solution I came up with is the following:
var i = 0;
while(array[i].id != "bb"){
i++;
}
alert(i) //returns 1
Is there an easier way that has cross-browser functionality? I tried $.inArray(id,array) but it doesn't work.
I don't see any problem with the complexity of your code, but I would recommend a couple of changes including adding some validation in case the value does not exists. Further more you can wrap it all in a reusable helper function...
function getArrayIndexForKey(arr, key, val){
for(var i = 0; i < arr.length; i++){
if(arr[i][key] == val)
return i;
}
return -1;
}
This can then be used in your example like so:
var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found
Here is a working example
NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.
var myArray = [your array];
var i = 0;
$.each(myArray, function(){
if (this.id === 'bb') return false;
i++;
})
console.log(i) // will log '1'
Update with modern JS.
let index
myArray.map(function(item, i){
if (item.id === 'cc') index = i
})
console.log(index) // will log '2'
inArray can't work with multidimensional array so try like the following
var globalarray= [
{"id" : "aa", "description" : "some description1"},
{"id" : "bb", "description" : "some more description"},
{"id" : "cc", "description" : "a lot of description"}];
var theIndex = -1;
for (var i = 0; i < globalarray.length; i++) {
if (globalarray[i].id == 'bb') {
theIndex = i;
break;
}
}
alert(theIndex);
Demo
You can use jQuery.each - http://api.jquery.com/jQuery.each/
var i;
jQuery.each(array, function(index, value){
if(value.id == 'bb'){
i = index;
return false; // retrun false to stop the loops
}
});
Object.keys(yourObject).indexOf(yourValue);