Iteration Syntax issue ForEach Vue.js - javascript

I tried an iteration using Vue.js
The result Got an error like this
[Vue warn]: Error in mounted hook: "TypeError: this.frontImages.forEach is not a function"
this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}};
this.frontImages.forEach(function(value, index) {
console.log(value);
}

.forEach() will only work for arrays.
If you need to iterate through the properties of a JSON object, then here is one way of doing that:
this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}};
printKeysAndValues(this.frontImages);
function printKeysAndValues(anyObject) {
Object.keys(anyObject).forEach( key => {
// in-case properties are nested objects
let value = JSON.stringify(anyObject[key]);
// let value = anyObject[key]; // for primitive nested properties
console.log(`${key} = ${value}`);
});
}

For array:
this.frontImages = [{frontA:{name:'frontAName'},frontB:{name:'frontBName'}}];
this.frontImages.forEach(function(value, index) {
console.log(value);
})
For only object iteration
this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}};
Object.values(this.frontImages).forEach(value => {
console.log(value);
});

Related

Finding a value within a matrix that includes nested arrays

I am trying to return a value that is situated within a matrix made up of arrays and nested arrays.
I am having trouble achieving this. My current approach is this:
//coords = 2,2,1,1,0
const addPrefix = (coords: []) => {
const completeCoords = (coords: []) => {
return coords.map((c) => {
return complex[c[0]][c[1]];
});
};
const values = completeCoords(coords);
console.log(values);
};
This current approach just returns this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'undefined')

Splice on computed item that maps elements

I'd like to ensure that all objects in an array are of type Item. If I do so, a splice does no longer work later.
This is how I do this:
computedItems: {
get()
{
//return this.modelValue;
return this.modelValue?.map((item) => new Item(item));
},
set(newValue)
{
this.$emit("update:modelValue", newValue);
}
}
This works fine but it seems to break reactivity, as:
removeItem(item) {
let key = this.computedItems.findIndex((i) => {
return item === i;
});
this.computedItems.splice(key, 1);
}
does not work (no error, list is just not being updated).
If I do
computedItems: {
get()
{
return this.modelValue;
},
set(newValue)
{
this.$emit("update:modelValue", newValue);
}
}
the splice does work as expected (but the items are not mapped to the specific object).
My questions:
How can I solve that?
Why is that the case? Is it a bad idea to map within the computed setter?
I'm not sure why it happens and cannot explain it very well.
Array and Object is keeping in memories. So it’s a pointer to memories.
The pointer was not changing and nothing is reactive. (Headache)
Can you try this code:
removeItem(item) {
const newArray = [...this.computedItems];
let key = newArray.findIndex(i => item === i);
newArray.splice(key, 1);
this.computedItems = newArray;
}

React: TypeError: Cannot read property 'newValue' of undefined

I have the following in componentDidMount
componentDidMount() {
const company = this.props.location.state.company;
const financials = this.props.location.state.financials;
let { values } = this.state;
values = EDITABLES.map((data) => { //EDITABLES is a const imported array
return {
id: data.id,
name: data.name,
value: financials[data.id]
newValue: "",
};
});
this.setState({
values,
});
}
However, if I console.log the values at the time of render, the first console log shows it as undefined, but the next one shows it as defined. I am also able to map the values in my render method without any problem.
render() {
const {
company,
financials,
values,
} = this.state;
console.log(values, "check")
My problem is that in my render method, I call a function {this.calculate(financial.id)}
calculate(financial) {
const { financials, values } = this.state;
console.log(values, "values");
let numerator;
if (financial === "tev_profit") { //this line is okay
let tev = values.find(o => o.id === "total_value");
console.log(tev, "here");
numerator = tev.newValue; //this line is causing error.
From the console log it seems as if tev is sometimes defined but other times not. I'm not sure where I'm going wrong because I also added this to my code but still facing the same typeError:
this.calculate = this.calculate.bind(this);
Update:
I have tried adding if(values) to my calculate function before I go into any other if block, but getting the same error
Issue
Array.prototype.find can return undefined if element isn't found.
The find() method returns the value of the first element in the
provided array that satisfies the provided testing function. If no
values satisfy the testing function, undefined is returned.
Solution
Check for valid tev object before accessing properties
if (financial === "tev_over_ltm_gross_profit") {
const tev = values.find(o => o.id === "total_enterprise_value");
if (tev) {
// tev exists
numerator = tev.newValue;
}

Implement Hash table in Javascript

I'm having trouble getting writing the getter method of my hash class based on what I have in the setter class.
The error I'm getting is: error: Uncaught TypeError: Cannot read property '1' of undefined
setItem = (key, value, value2) => {
const idx = HashStringToInt(key, this.table.length);
if (this.table[idx]) {
this.table.push([key,[value, value2]]);
} else {
this.table[idx] = [[key, [value, value2]]]
}
}
getItem = key => {
const idx = HashStringToInt(key, this.table.length);
if (!this.table[idx]) {
return null;
}
return this.table[idx].find(x => x[0] === key)[1]; //this doesn't work
}
Changing:
this.table.push([key,[value, value2]]);
To:
this.table[idx].push([key,[value, value2]]);
Seems to give me the desired results

TypeScript: TypeError: Cannot read property 'push' of undefined

I'm trying to make an application with Angular 2. Now I ran into a problem which I can't solve.
One of the functions of an array should be push(object: T);
I defined an array of an object that I made. But when I try to add values to this array I receive the following error: TypeError: Cannot read property 'push' of undefined.
One of the main causes of this error is people forgetting to define their array. But I'm defining it, I tried it in multiple ways but still the same error.
export class Home {
activeDossiers: Array<Dossier> = new Array();
//Also tried:
//activeDossiers: Dossier[] = [];
//activeDossiers = [];
//activeDossiers: Array<Dossier> = [];
constructor() {
var dossierApi = new DossierApi();
dossierApi.getActiveDossiers().then((dossiers) => {
dossiers.forEach(function (obj, i) {
console.log(obj);
if(obj.dossierType === Values.Visible) {
this.activeDossiers.push(obj);
}
});
});
}
}
You are using the anonymous function() syntax for the callback; this syntax does NOT preserve the this. Instead do:
dossiers.forEach((obj, i) => { // IMPORTANT PART HERE!!!
console.log(obj);
if(obj.dossierType === Values.Visible) {
this.activeDossiers.push(obj);
}
});

Categories