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]);
}
}
Related
file structure
this._formService.arraySteps[j].profile[i].nom = newValue;
where i and j are indexes
How can I make this works using variable instead of text.
I've tried the following where
tmpKeyName = "profile"
keyObject = "nom"
this._formService.arraySteps[j][tmpKeyName][i][keyObject];
Thanks
Assuming that your array/object structure is correct, your code would work:
// let's assume that this._formService.arraySteps was the following array of objects:
var arraySteps = [
{
profile: [
{nom: "something"}
]
},
{
profile: [
{nom: "something else"}
]
},
{
profile:[
{nom: "something totally different"}
]
}
];
var tmpKeyName = "profile";
var keyObject = "nom";
// Looping through that array:
for(var j = 0; j < arraySteps.length; ++j){
// Looping through the objects in the array:
for(var i = 0; i < arraySteps[j][tmpKeyName].length; ++i){
console.log(arraySteps[j][tmpKeyName][i][keyObject]);
}
}
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 need to loop through array and each array in array that has extra values, push them to their parent array as separate item. I hope this makes sense..
This is the structure of my initial array:
{type:
[ 0:
value: "tomato"
],
[ 1:
{value: "apple",
[ extras:
[ 0: { value: "green" } ],
[ 1: { value: "red" } ]
]
],
[ 2:
value: "pineapple"
]
}
What the result would have to look like:
[type:
[ 0:
tomato
],
[ 1:
apple,
green,
red
],
[ 2:
pineapple
]
]
What I've tried and failed: (I also commented the error I get on right line)
var response = /* json of first codeblock in question is response from ajax */;
var items = JSON.parse( response );
var type = Object.keys( items )[0];
var myArray = []
var count = items[type].lenght;
//Loop through main items in "type"
for( i = 0; i < count; i++ ) {
var value = items[type][i][value];
myArray[type][i] = [value]; //Uncaught TypeError: Cannot set property '0' of undefined
if( items[type][i][extras] ) {
var extracount = items[type][i][extras].lenght;
//Loop through extras
for( k = 0; k < extracount; k++ ) {
var extra = items[type][i][extras][k][value];
myArray[type][i].push( extra );
}
}
}
My main problem that I don't understand and that seems to be the problem in my example as well:
If I declare an empty array, how do I:
push an item to that array also declaring a new array around that item?
push another item to that array that was made around the first item?
This is what I believe you want. The following code may be incorrect, because I'm approximating what I believe your items object contains.
var items = {
type: [
{
value: "tomato"
},
{
value: "apple",
extras: [
{
value: "green"
}, {
value: "red"
}
]
},
{
value: "pineapple"
}
]
};
var myArray = {
type: []
};
var count = items['type'].length;
//Loop through main items in "type"
for (i = 0; i < count; i++) {
var subarray = [];
subarray.push(items['type'][i]['value']);
if (items['type'][i]['extras']) {
var extracount = items['type'][i]['extras'].length;
//Loop through extras
for (k = 0; k < extracount; k++) {
var extra = items['type'][i]['extras'][k]['value'];
subarray.push(extra);
}
}
myArray['type'].push(subarray);
}
Some notes:
You will definitely need to learn the difference between an array and an object in javascript. There are plenty of resources online for this.
When retrieving/manipulating a property prop from an object obj (i.e. for a key-value pair), you will need to use obj.prop or obj['prop']. Note the use of a string in the latter example.
For an array arr, you should use arr.push(value) to push a new value onto the array.
Your problem is here:
var value = items[type][i][value];
you should change it to
var value = items[type][i].value;
I'm tryign to write code that will loop through an array "productsArray" and match it against my productPropertyArray to pull matching information.
however productsArray is an array in an array that contains an object with the data. My Question is how can I loop through both arrays and then return the matching data.
Current function:
var pList = productsArray
if (productPropertyArray.length === 0 || productsArray.length === 0) return [];
for (var i = 0; i < pList.length; i++) {
for (var j = 0; j < pList[i].length; j++) {
if (pList[i][j] === productPropertyArray) {
return productPropertyArray;
} else {
continue;
}
}
}
return [];
};
example of pList:
productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": 1}],
[{"sellAlone": false,"test": 1}]
];
example of productPropertyArray: (its an argument thats replaced by the following)
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
productPropertyArray is just an argument in the function which is replaced by productSKUArray The setup goes like this: function(productProperty, productPropertyArray, productsArray) {
productProperty is just a string that contains sku or productID
any ideas are appreciated. thanks.
Check this out:
http://jsfiddle.net/v9d7bjms/2/
function find() {
var productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": "00544MF24F575"}],
[{"sellAlone": false,"test": 1}]
],
pList = productsArray,
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
// All arrays matching your productsSKUArray
var findings = productsArray.filter(function (productProperty) {
// .some returns true after finding first matching element (and breaks the loop)
return productProperty.some(function (obj) {
var keys = Object.keys(obj);
// We need to get all the "values" from object so we interate over
// the keys and check if any value matches something from productSKUArray
return keys.some(function (key) {
// Check if value exists in productsSKUArray
return productSKUArray.indexOf(obj[key]) > -1;
});
});
});
return findings;
}
console.log(find());
.filter will return all arrays containing objects with values from productSKUArray.
See Array.prototype.filter, Array.prototype.some and Array.prototype.indexOf for method reference.
The inner if needs to refer to pList[i][j].
This will output [{sku: "131674"}, {sku: "84172"}].
var matchingData = [];
for(var productProperties in productsArray){
var pp = productsArray[productProperties];
for(var property in pp) {
var p = pp[property];
for(var propertyName in p){
var propertyValue = p[propertyName];
for(var i in productSKUArray){
if(propertyValue == productSKUArray[i]){
matchingData.push(p);
break;
}
}
}
}
}
but this is just the brute force solution.
I want to access salesId of json array but sales is an array also, so do loop twice?
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
for (var i in json) {
for (var j in json[i].sales) {
var result = json[i].sales[j].salesId; // here "result" will get salesId
}
}
See by yourself : here
How do you want the output?
json.map(function(x){ return x.sales.map(function(y){return y.salesId})})
returns ids per object
"[[123,456],[789,111213]]"
You can use inner loop instead, incase salesId is dynamic in sales.
for(var i=0;i<json.length;i++){
salesItem = json[i].sales;
for(var j=0;j<salesItem.length;j++){
var item = salesItem[j];
console.log(item.salesId);
}
}
If you don't care about the id you could simply flatten the array like so:
var newArray = json.reduce(function(p,c,i){
return i>1 ? p.concat(c.sales) : p.sales.concat(c.sales);
});
which will give you:
[ // newArray
{'salesId':123},
{'salesId':456},
{'salesId':789},
{'salesId':111213}
]
You could also use reduce to return just an array of salesId too if you wanted.
You don't need to loop twice
//loop through the json array that holds objects
for (var i=0; i<json.length; i++) {
var obj = json[i]; //reference to each object
var sales = obj.sales;
sales.forEach(function(element, index) {
console.log(element.salesId);
});
}
Here are two other ways. Not suggesting these are better, just 'other' ways.
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
one way:
var results = [];
for(i=0;i<json.length;i++){
results.push ( JSON.stringify(json[i].sales).match(/(\d+)/g,function($1){
return $1
}))
};
results; // [["123", "456"], ["789", "111213"]]
another way:
var str;
for(i=0;i<json.length;i++){
str = str + JSON.stringify(json[i].sales);
};
str = str.match(/(\d+)/g,function($1){
return $1
})
str; //["123", "456", "789", "111213"]