I have an array of javascript objects (of undefinite length).
var records =
[
{ query_result_id: 373,
url: 'https://www.example1.com/hheyue',
title: 'title1',
uselesskey3: 'yo',
uselesskey4: 'ya',
max_email_nb_sent: 1 },
{ query_result_id: 375,
url: 'https://www.example2.com',
title: 'title2',
uselesskey3: 'yo',
uselesskey4: 'ya',
max_email_nb_sent: null }
//and so on...]
I am today creating a new object called parametersObj (to keep records unchanged for immutability reasons) based on records by doing a certain number of things:
var parametersObj = records
//remove useless keys
.map(({
title,uselesskey3, uselesskey4, max_email_nb_sent,
...item
}) => item)
//add new needed keys
.map(s => (
{
...s,
status: process.env.CONTEXT === "production" ? "prod" : "dev",
triggered_at: new Date().toLocaleString()
}
));
This works perfectly.
But what I am trying to do now is to add on the code above when I create parametersObj a method where before removing useless keys (the first .map above), I add a new key called email_nb for each javascript object which is equal either to :
0ifmax_email_nb_sentisnullmax_email_nb_sent + 1ifmax_email_nb_sentisnot null
The expected value of parametersObj after we execute the script should be:
[
{ query_result_id: 373,
url: 'https://www.example1.com/hheyue',
title: 'title1',
email_nb: 2,
status: "prod",
triggered_at: '2019-9-30 23:11:12'
},
{ query_result_id: 375,
url: 'https://www.example2.com',
title: 'title2',
email_nb: 0,
status: "prod",
triggered_at: '2019-9-30 23:11:12' }
//and so on...]
I can use ES6 and prefer to if possible as usually more concise.
I tried this but this below did not work
var parametersObj = records
//adding the new key email_nb
.map(s=> s["email_nb"] = s["max_email_nb_sent"] + 1)
//remove useless keys
.map(({
title,uselesskey3, uselesskey4, max_email_nb_sent,
...item
}) => item)
//add new needed keys
.map(s => (
{
...s,
status: process.env.CONTEXT === "production" ? "prod" : "dev",
triggered_at: new Date().toLocaleString()
}
));
but then parametersObj is becoming just equal to [1, 1] which is very wrong...
Feedback on some answers
Tried:
var parametersObj = records
//adding the new key email_nb
.map(item =>
{ ...item,
email_nb: item.max_email_nb_sent ?
item.max_email_nb_sent + 1 : 0
}
)
//remove useless keys
.map(({
title,uselesskey3, uselesskey4, max_email_nb_sent,
...item
}) => item)
//add new needed keys
.map(s => (
{
...s,
status: process.env.CONTEXT === "production" ? "prod" : "dev",
triggered_at: new Date().toLocaleString()
}
));
but I get error:
Uncaught SyntaxError: Unexpected token ...