Need to iterate through arrays having objects Vue - javascript

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>

Related

How to improve the performance of 'for loop' to integrate some objects in JS

I have three for loop as below to integrate their objects.
The problem is the length of 'cars' array is 20,000.
So it should runs every 20,000 times for finding same id between company.user and cars.
But the id of cars is unique.
Can I reduce this repeat number in JS?
I want to reduce the taking time.
Thank you for reading it.
p.s. I uploaded same question adding the concrete logic inside of for loop.
for (let i = 0; i < company.length; i += 1) {
for (let j = 0; j < company[i].user.length; j += 1) {
for (let k = 0; k < cars.length; k += 1) {
if (company[i].user[j].id === cars[k].id) {
company[i].user[j] = {
...company[i].user[j],
...cars[k]
}
}
}
}
}
If there is only 1 match then use break after you found that item. Imagine you find that item at index 1 for example, then the loop would still continue and do 19998 loops. Because of the information that you know there is only 1 possible match you can break it there.
if (company[i].user[j].id === cars[k].id) {
company[i].user[j] = {
...company[i].user[j],
...cars[k]
}
break;
}
for (let i = 0, leni = company.length;; i < leni ; i += 1) {
for (let j = 0, lenj = company[i].user.length; j < lenj; j += 1) {
for (let k = 0, lenk = cars.length; k < lenk; k += 1) {
if (company[i].user[j].id === cars[k].id) {
company[i].user[j] = {
...company[i].user[j],
...cars[k]
}
break; // match only the first one, then stop searching for cars
}
}
}
}
Answer based on test results from https://jsperf.com/caching-array-length/4
Spread left in base on
https://thecodebarbarian.com/object-assign-vs-object-spread.html
this will optimize your code a little more, but ziga1337 is right, the only effective way is to sort your two objects
// company: [ { user: [ { id: '?1'
// cars: [ { id: '?2'
for (let iCompagny of compagny) {
for (let iUser of iCompagny.user) {
let fCar = cars.find(xCar.id===iUser.id)
if (fCar) Object.assign(iUser, fCar)
}
}
in case there is always a car.id unique to each user.id:
let indexCars = cars.reduce((a,c)=>{ a[c.id]=c; return a },{})
compagny.forEach(iCompagny=>{
iCompagny.user.forEach(iUser=>{ Object.assign(iUser, indexCars[iUser.id]) })
})

Nested for loop functioning

I have trouble understanding nested for loops
posts: [
{
title: 'lorem',
comments: [
{
content: 'lorem'
user: 'John'
},
...
]
},
...
]
My goal here is to get all the comments from a specific user, in all the posts.
Here is how I proceed (I'm using mongoose, I get the user from an auth middleware)
const postsList = await Post.find();
var userComments = [];
for (var i = 0; i < postsList.length; i++) {
if (postsList[i].comments.length > 0) {
for (var j = 0; j < postsList[i].comments[j].length; i++)
if (postsList[i].comments[j].user == req.user.id) {
userComments.push(comments[j]);
}
}
}
When I try this, I get a Cannot read property 'length' of undefined. I think my error is in the second for loop, but I can't get why. Any help please?
Mark Meyer in the comments is correct.
comments is an array inside of each post object. comments[j] would refer to an element inside the comments array. comments[j].length doesn't make sense because in order to run your nested j for loop, which iterates over the comments array, you want the length of the comments array, not the length of one of its elements.
Here's the line that needs to be fixed:
const postsList = await Post.find();
var userComments = [];
for (var i = 0; i < postsList.length; i++) {
if (postsList[i].comments.length > 0) {
// for (var j = 0; j < postsList[i].comments[j].length; i++)
// fixed version below
for (var j = 0; j < postsList[i].comments.length; i++)
if (postsList[i].comments[j].user == req.user.id) {
userComments.push(comments[j]);
}
}
}

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);

Iteration on JSON of JSON

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]);
}
}
}

Alphabetize items in a JavaScript object?

Say I have an object that looks like this:
countrylist:{
regions:[
{
region: "Europe",
countries: [
{
"country":"Albania",
"href":"eu",
"locale":"en_al"
},
{
"country":"France",
"href":"eu",
"locale":"en_fr"
},
{
"country":"Ireland",
"href":"eu",
"locale":"en_ie"
}]
},
region: "Asia",
countries: [
{
"country":"China",
"href":"as",
"locale":"ch"
},
{
"country":"Japan",
"href":"as",
"locale":"jp"
},
{
"country":"Thailand",
"href":"as",
"locale":"th"
}]
}
]}
If you could see the whole object, you would see that it's grouped by region, and the countries within each region are sorted alphabetically. However, I need to populate a dropdown menu of all the countries, alphabetized, but not by region. What's the cleanest method to go about sorting these items?
I originally pushed the country field to an empty array and sorted that. However, I need to preserve the relationship between the country field and its corresponding href and locale fields.
Initialize an empty array, then go through the regions and append all the countries to that array. When you're done, sort the array.
var countries = [];
for(var i = 0; i < countrylist.regions.length; i++)
Array.prototype.push.apply(countries, countrylist.regions[i].countries);
countries.sort(function(a, b) {
return a.country > b.country;
});
console.log(countries);
http://jsfiddle.net/Jehsb/
You need to walk your structure and create an array of country names. You can then sort the array, and you're done.
var arr = [];
for(var i = 0; i < countryList.regions.length; i++){
var countries = countryList.regions[i].countries;
for(var j = 0; j < countries.length; j++){
arr.push(countries[j].country);
}
}
arr.sort();
If you need the other information as well, what you'd need is a flat array of all country objects, and then apply a custom sort function:
var arr = [];
for(var i = 0; i < countryList.regions.length; i++){
var countries = countryList.regions[i].countries;
for(var j = 0; j < countries.length; j++){
arr.push(countries[j]);
}
}
arr.sort(function(xx,yy){
return xx.country < yy.country ? -1 : 1;
});

Categories

Resources