Iteration on JSON of JSON - javascript

I have this problem: I have a JSON object and I want to iterate on it in a javascript function, but it is composed of other JSON objects.
It is, for example:
[
{"id"="1", "result"=[{"name"="Sam","age"="12"},{"sport"="soccer"}]},
{"id"="2", "result"=[{"name"="Paul","age"="43"},{"sport"="basketball"}]}
]
And I would iterate on it to work with values, in this way:
1) on first iteration: I want to work with: "Sam", "12", "soccer"
2) on second iteration: I want to work with: "Paul", "43", "basketball"
and so on.
Can you help me for this problem?

First you must fix your object literal. You must use : not = for the key-value pairs.
After that you can iterate in the following way:
var obj = [ {"id":"1", "result":[{"name":"Sam","age":"12"},{"sport":"soccer"}]},
{"id":"2", "result":[{"name":"Paul","age":"43"},{"sport":"basketball"}]}];
for (var i = 0; i < obj.length; i += 1) {
console.log("Name", obj[i].result[0].name);
console.log("Age", obj[i].result[0].age);
console.log("Sport", obj[i].result[1].sport);
}
If you want to do the whole traversal with loops you can use:
var obj = [ {"id":"1", "result":[{"name":"Sam","age":"12"},{"sport":"soccer"}]},
{"id":"2", "result":[{"name":"Paul","age":"43"},{"sport":"basketball"}]}];
for (var i = 0; i < obj.length; i += 1) {
for (var j = 0; j < obj[i].result.length; j += 1) {
var current = obj[i].result[j];
for (var prop in current) {
console.log(prop, current[prop]);
}
}
}

Related

Need to iterate through arrays having objects Vue

I have an array list and each list are groups of objects. I need to iterate through each group and check if an object in a list satisfies a condition.
This is what have been able to do but, doesn't iterate through each object.
for (i = 1; i <= this.portfolioDetails.length; i++) {
for (var j = 1; j < this.portfolioDetails[i].length; j++)
{
console.log(portfolioDetails[i][j]);
}
}
This is the list of array objects:
portfolioDetails:Array[3]
0:Object
ACCOUNTID:"S1001"
ACCOUNTNAME:"Bla bla bla"
ACCRUEDINTERESTALL:0
PRICE:0.69
UNITS:60.49
VALUE:41.98
product:null
1:Object
ACCOUNTID:"S1002"
ACCOUNTNAME:"blo bla blo"
ACCRUEDINTERESTALL:0
PRICE:0.69
UNITS:60.49
VALUE:41.98
product:null
2:Object
ACCOUNTID:"S1003"
ACCOUNTNAME:"blik blik blik"
ACCRUEDINTERESTALL:0
PRICE:0.69
UNITS:60.49
VALUE:41.98
product:null
This is simple JavaScript and has nothing to do with VueJS per se. The reason your iteration is not working is because you start with i = 1 while in coding you start with an index of 0. Also, you are including the last number with your comparison statement <= which is not in the array (because you start counting at 0, not at 1). On top of that, you can just print out object values by their keys. This all adds up to something like this:
for (let i = 0; i < this.portfolioDetails.length; i++) {
console.log(this.portfolioDetails[i].ACCOUNTID)
}
Your top loop iterate should look like:
for (i = 0; i < this.portfolioDetails.length; i++) { ... }
This code should work:
for (let i = 0; i < this.portfolioDetails.length; i--) {
for (let j = 0; j < this.portfolioDetails[i].length; j--)
{
// Check conditions here
if (this.portfoiloDetails[i][j].ACCOUNTID === 'S1002') {
// Actions goes here
}
}
}
Hi the given list of array objects is unclear but if you are trying to iterate over JSON data type, you can use the code below. This code dynamically discovers the properties and return the value of each property.
<script>
var portfolioDetails = { 'data': [
{ 'fname': 'joe', 'lname': 'smith', 'number': '34'} ,
{ 'fname': 'jim', 'lname': 'Hoff', 'number': '12'} ,
{ 'fname': 'jack', 'lname': 'jones', 'number': '84'}
] };
//iterate over the records
for (i = 0; i < portfolioDetails["data"].length; i++) {
var data = this.portfolioDetails["data"][i];
var propertiesCount = Object.getOwnPropertyNames(data).length;
//iterate over the properties of each record
for (var j = 0; j < propertiesCount; j++)
{
var propName = Object.getOwnPropertyNames (data)[j];
console.log(portfolioDetails["data"][i][propName]);
}
}
</script>

How to use a key array to remove specific items from a main array?

First of all thank you to whoever reads this whole question. I am having trouble writing a function that can take a key array and use the indices to remove like items from a main array.
My main Array
var mainArray = [
{fruit:"apple",color:"red"},
{fruit:"orange",color:"orange"},
{fruit:"banana",color:"yellow"},
{fruit:"apple",color:"red"},
{fruit:"banana",color:"yellow"},
{fruit:"mango",color:"greenishyellowishred"}
]
Array of items will be added to this mainArray and I need to remove multiple items at a time.
My key Array
var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}]
I am attempting to remove the "apple" and the "banana" by using a for loop to decrement through the array to maintain the integrity of the mainArray.
for(var i = mainArray.length - 1; i > -1; i--) {
for(var j = keyArray.length - 1; j > -1; j--) {
if(mainArray[i].fruit === keyArray[j].fruit) {
mainArray.splice(i, 1)
keyArray.splice(j, 1)
}
}
}
My issue comes when I am trying to read mainArray[i].fruit if i = 0
Thanks in advance for any help possible.
Try the following way:
var mainArray = [
{fruit:"apple",color:"red"},
{fruit:"orange",color:"orange"},
{fruit:"banana",color:"yellow"},
{fruit:"apple",color:"red"},
{fruit:"banana",color:"yellow"},
{fruit:"mango",color:"greenishyellowishred"}
];
var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}];
var tempArray = [];
for(let j = 0; j < keyArray.length; j++) {
for(let i = 0; i < mainArray.length; i++) {
if(mainArray[i].fruit === keyArray[j].fruit) {
tempArray.push(mainArray[i]);
}
}
}
mainArray = mainArray.filter( function( el ) {
return !tempArray.includes( el );
});
console.log(mainArray);

Not getting expected results from for loop

I'm making a javascript neural network and trying to put some entries into an object using for loops but I'm not getting the result I want.
I want to be able to get an object looking like:
{0 : {neuron1Sum : null}}
And I want to loop it to create multiple neurons and layers. It might be easier to understand once you see the code.
hiddenLayers : function() {
for(var i = 0; i < arguments.length; i++) {
numberOfNeurons = arguments[i];
hiddenLayer = {};
for (var j = 0; j < numberOfNeurons - 1; j++) {
hiddenLayer[i] = ["neuron" + j + "Sum"];
hiddenLayer[i]["neuron" + j + "Sum"] = null;
}
}
},
Your hiddenLayer should be defined as array and hiddenLayer[i] should be defined as object. Then put each element to object like this way.
hiddenLayers : function() {
var hiddenLayer = []; // defined as array
for(var i = 0; i < arguments.length; i++) {
numberOfNeurons = arguments[i];
hiddenLayer[i] = {}; //defined as object
for (var j = 0; j < numberOfNeurons - 1; j++) {
hiddenLayer[i]["neuron" + j + "Sum"] = null;
}
}
return hiddenLayer;
/*
will return something like :
[
0 : {neuron1Sum : null, neuron2Sum : null},
1 : {neuron1Sum : null, neuron2Sum : null}
]
*/
},
Looks like you need to move a couple identifiers around and initialise an Array before the inner loop
// ...
hiddenLayers: function() {
var numberOfNeurons,
hiddenLayer = [], // keep this across all the loops
temp, // to store objects as we make them
i, j;
for (i = 0; i < arguments.length; ++i) {
numberOfNeurons = arguments[i];
hiddenLayer[i] = []; // remember to initialise
for (j = 0; j < numberOfNeurons - 1; ++j) {
temp = {};
temp["neuron" + j + "Sum"] = null;
hiddenLayer[i].push(temp);
}
}
return hiddenLayer; // remember to return
},
// ...
This code now produces something like
[
[
{neuron0Sum: null},
{neuron1Sum: null}
],
[
{neuron0Sum: null},
{neuron1Sum: null}
]
]
Starting in ES6 we will be able to use expressions in the property names of Object literals, e.g.
{
["foo" + "bar"]: "baz"
}
// produces
{
"foobar": "baz"
}
If you want your code to work in production right now, don't use this feature yet (maybe in a year or two)
I don't think that code is doing what you want, but I'm not sure what you want..
This assignment:
hiddenLayer[i] = ["neuron" + j + "Sum"];
sets hiddenLayer[i] to an array containing a single string. It's equivalent to this:
hiddenLayer[i] = [];
hiddenLayer[i][0] = "neuron" + j + "Sum";
Then this assignment:
hiddenLayer[i]["neuron" + j + "Sum"] = null;
Treats hiddenLayer[i] as a generic Object (associative array, map, hash, dictionary) and sets a named property (with the same name as that string) to null. So if i is 0 and j is 0, you get an object that looks like this:
{
0: "neuron0Sum",
neuron0Sum: null
}
I suspect that's not what you're trying to accomplish...

Get an object from two nested array in Javascript

I want to have an object from two arrays and I did it in the following way.
for (var j = 0; j < rawDataRows.length; j++) {
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
var rowValue = rawDataRows[j];
// here I do got the right value for category
console.log(category);
console.log(rowValue);
// but the following line doesn't interpret category as a variable
formattedDataRows.push({category: rowValue});
}
}
I was assuming I can get something like :
[{"category1": "value1"},{"category2": "value2"}, {"category3": "value3"}]
However, it turned out I got:
[{"category": "value1"}, {"category": "value2"}, {"category": "value3"}]
Can anyone point me where I am wrong? Also, if you have a better way achieving the goal, leave a comment please. Javascript only no jQuery or other framework. Thanks!
Object literal syntax In ECMAScript 5 and lower doesn't allow you to specify a variable identifier as property name. Instead create the object first and then use bracket notation.
var o = {};
o[category] = rowValue;
formattedDataRows.push(o);
With ECMAScript 6, you can do this:
formattedDataRows.push({[category]: rowValue});
though of course support for that syntax is limited at this point in time.
If you want both values to increment together (as it seems), also assuming the length of categories is the same length as rawdataRows, I think you really want a single loop instead of two loops:
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
var rowValue = rawDataRows[i];
You can use categories[i].toString(); to get strings as you wished:
var categories = ["category1", "category2", "category3"];
var rawDataRows = ["value1", "value2", "value3"];
var formattedDataRows = [];
for (var j = 0; j < rawDataRows.length; j++) {
for (var i = 0; i < categories.length; i++) {
var category = categories[i].toString();
var rowValue = rawDataRows[j].toString();
var tmpObj = {}
tmpObj[category] = rowValue
formattedDataRows.push(tmpObj);
//formattedDataRows.push({[category]: rowValue});
}
}
document.write(JSON.stringify(formattedDataRows))

How can I add each element of one array to corresponding elements in other arrays with javascript or angular

I need to add the elements of arrays together in order, very similar to the question at [How can I add each element of one array to another one's corresponding element using a ParallelStream?, but I'm using javascript and angular. My arrays can come in with any amount of elements up to 31 (days), but they will all always be the same amount of elements across each data object.
$scope.test31days = {
"change_series": [
{ "data": [0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,0,0],
"name": "EMERGENCY",
"color": "#904040"},
{ "data": [0,1,3,0,0,0,0,1,2,3,3,0,0,0,2,1,1,1,0,0,1,1,3,3,1,0,0,1,2,2,0],
"name": "MINOR",
"color": "#333"},
{ "data": [0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0],
"name": "MAJOR",
"color": "#666"}
],
"change_title": "CHANGES"
}
My console output tells me I'm separating the elements correctly (to some extent), but when I run this with the if/else if statement, I crash the browser, so I know I'm screwing something up.
$scope.getTotalChanges = function(){
var series = $scope.test31days.change_series;
var arry = [];
for(var i = 0; i < series.length; i++){
// console.log('change_series loop #', i);
// console.log('change_series.data length', series[i].data.length);
var seriesData = series[i].data;
// console.log('series[i].name', series[i].name)
// console.log('seriesData', seriesData)
for(var j = 0; j < seriesData.length; j++){
console.log('For inner #', j);
console.log('seriesData #', seriesData[j]);
if (j = 0) {
arry = seriesData;
} else if (j > 0) {
arry[j] += seriesData[j]
};
}
}
// return series;
console.log('arry ', arry);
return arry;
};
My end goal is to have a single array of the data for the 31 (days)
var series = $scope.test31days.change_series;
var dataLength = series[0].data.length;
var result = Array.apply(null, new Array(dataLength)).map(Number.prototype.valueOf,0); //initialize result array with zeros
for(var i = 0; i < series.length; i++) {
for(var j = 0; j < dataLength; j++) {
result[j] += series[i].data[j];
}
}

Categories

Resources