forEach not changing values of array - javascript

availableButtons.forEach(function(part, index) {
console.log(this[index].title)
// this[index].title = intl.formatMessage(this[index].title);
}, availableButtons)
The code above prints the console as follows:
{id: "abc.btn.xyz", defaultMessage: "someMessage"}
This confirms that each object has an id but when I try to execute the commented code it throws an error saying [#formatjs/intl] An id must be provided to format a message.
I used the same array but only a single object separately as follows intl.formatMessage(availableButtons[0].title); this gave me the required result I am just not able to figure out. I tried various ways of passing values in forEach, what am I missing?

forEach does not actually mutate arrays. it's just a shorthand loop called on the array. It's hard to suggest a solution because your intent is not clear.
availableButtons = availableButtons.map(button => {
//do your mutations here
}
might be a start

I think Array#map works better for in this vade
availableButtons.map(part => {
return {
...part,
title: intl.formatMessage(part.title)
};
});

Access the array (availableButtons) directly and update (mutate) with forEach.
availableButtons.forEach(function (part, index) {
console.log("before: ", availableButtons[index].title);
availableButtons[index].title = intl.formatMessage(this[index].title);
console.log("after: ", availableButtons[index].title);
});

Related

Changes in .forEach() have no effect?

So let me preface this with the fact that I'm doing this coding in Codecademy so maybe its just that being weird.
I am trying to remove all punctuation from an array (dupBW) and set everything to lowercase.
My code works fine within the forEach, the console.log shows that. But then dupBW is unaffected when I log it out at the end.
Thanks for the help.
dupBW.forEach(dupWord => {
if(puncArray.includes(dupWord[dupWord.length-1])) {
dupWord = dupWord.slice(0, dupWord.length-1);
dupWord = dupWord.toLowerCase();
console.log(dupWord);
}
});
console.log(dupBW.join(' '));
Change forEach to map and return dupWord at the end, and it will work; by assigning the array to the newly returned one. Array.prototype.map returns a new array with the return values of the callbacks.
dupBW = dupBW.map(dupWord => {
if(puncArray.includes(dupWord[dupWord.length-1])) {
dupWord = dupWord.slice(0, dupWord.length-1);
dupWord = dupWord.toLowerCase();
console.log(dupWord);
}
return dupWord;
});
console.log(dupBW.join(' '));
If you see in the documentation for .forEach() you will find that forEach does not modify the array it is called on. For that, you can use regular for loop or map or reduce.
You can do the following,
let res = dupBW.map(dupWord => {
if(puncArray.includes(dupWord[dupWord.length-1])) {
dupWord = dupWord.slice(0, dupWord.length-1);
dupWord = dupWord.toLowerCase();
console.log(dupWord);
}
return dupWord;
});
console.log(res.join(' '));

How to use array.push to add value to an array?

I would like to add a value with array.push to my first element of array [0] to the field yesterday, I don't know very well what the structure is to be able to add this value. try the following way
var cumpleaños = [
{
ayer: "",
},
{
hoy: "12-07-20",
} ,
{
mañana: "12-08-20"
}
];
cumpleaños.push([0].ayer.("12-06-20"))
console.log(cumpleaños[0].ayer)
Thank you very much for the help!
You don't need to push anything since you're not adding a new value, you're just modifying an existing value:
cumpleaños[0].ayer = "12-06-20";
As a side note, your data structure would be much more effectively represented by a single object not inside an array:
const cumpleaños = {
ayer: "12-06-20",
hoy: "12-07-20",
mañana: "12-08-20"
};
You would do assignment to the first element of the array. (If the oder is always the same)
cumpleaños[0].ayer = "12-06-20"

Access nested object JSON array with Javascript

Using Logger.log(response.data.phone), I'm getting this in my log:
[{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}]
What I want is to return the two phone numbers as 5558675309, 6108287680.
I've tried Logger.log(response.data.phone.value) and that doesn't work. I've tried ...phone['value'], I've tried ...phone[0].value and this one does return the first phone number 5558675309. But I would like it to return all of the value values whenever I put in the phone key. So how would I modify the logger?
response.data.phone is an array you can try looping through it:
Logger.log(response.data.phone.map(phone => phone.value).join(', '));
const response = {data: {phone : [{label:'work', primary:true, value:5558675309}, {label:'work', value:6108287680, primary:false}, {value:6105516373, label:'work', primary:false}] } }
const Logger = { log : console.log};
Logger.log(response.data.phone.map(phone => phone.value).join(', '));
response.data is an array, response.data.phone does not exist. What you want is response.data[n].phone for an integer n. You can do this with a forEach loop.
response.data.forEach((element) => Logger.log(element.phone.value));
If for whatever reason you need support for older browsers you can use the older function syntax:
response.data.forEach(function(element){
Logger.log(element.phone.value)
});

Return filtered array in javascript

I though this was going to be straightforward. I have a dataset containing (foreach country) name, imfcode, lat,lon. I want to pass a code to a function that will filter the dataset returning the info that correspond to the code passed to it. So if I pass 512 I should get information relating to Afganistan. here my function, would someone mind telling me what I'm doing wring
function loadTrade(imfCode) {
console.log ("Country code= ",imfCode)
var sourceCountry=dataset.filter function(el){
return el.imfcode===imfCode
}
console.log ("Source country= ",sourceCountry)
}
I keep getting an unexpected token and just can't see it. Many thanks
You missed the Parenthesis after dataset.filter
Change it to :
function loadTrade(imfCode) {
console.log ("Country code= ",imfCode)
var sourceCountry=dataset.filter(function(el){
return el.imfcode===imfCode;
});
console.log ("Source country= ",sourceCountry);
}

can't get nested forEach to work in Javascript

So I guess the title is selfexplanatory. I have some code with nested forEach loops inside it. The loops are iterating over an array of chapter objects. Each object can have multiple child nodes and they again can have multiple child nodes, and so on.
I want to end up with one array which contains nested arrays with the child nodes.
So far my code looks like this:
exports.chapter = function(req, res) {
var chapters = [],
result = [];
chapters = exports.index(req, res);
chapters.forEach(function(chapter) {
if(chapter.orphan){
result.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
function getChildren(siblings) {
var children = [];
chapters.forEach(function(chapter) {
if($.inArray(chapter, siblings)){
children.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
return children;
};
};
I don't get any errors except for my page not loading. It doesn't write anything in my console. I think it's a problem in the setup but I'm unable to find out where at the moment. Really hope you guys can help.
Most likely problem is here:
if($.inArray(chapter, siblings)){
$.inArray is a horribly misnamed method: It returns an index, or -1 if not found, not a flag as the name implies. -1 is, of course, truthy; and 0 (a valid index), is falsey, so your if probably wants to be
if($.inArray(chapter, siblings) != -1){
// We found it...
}
or possibly
if($.inArray(chapter, siblings) == -1){
// We didn't find it
}
It's a bit strange.. I don't understand why you're using 'add' instead of 'push' method. If I try to "add" an object to an array I get an usual error. Don't you?

Categories