'How Can I Make a conditional with return in a .map without get out of main function?
My objective is create this object:
{
name: string,
birthday: date
}
by this array:
const dataArray = [
{
"id": "name",
"type": "string"
},
{
"id": "birthday",
"type": "date"
}
]
So, I create a .map of the array, like this:
const inputsValues = {};
dataArray.map(item => {
if(item.type === "date"){
inputsValues[item.id] = new Date(item.value);
return; // this line is the problem
}
inputsValues[item.id] = item.value;
});
Is there a option to make a return in this function without use else?
Solution 1:[1]
const data = [
{id: "name", type: "string", value: "John"},
{id: "birthday", type: "date", value: "02.02.22"},
{id: "holiday", type: "date", value: "03.03.33"}
]
const inputsValues = data
// the "return" function - filters all non "date" items
.filter(item => item.type != "date")
// the map + inputsValue combination in one function
.reduce((values, item) => ({[item.id]: item.value, ...values}), {})
console.log(inputsValues)
Solution 2:[2]
const dataArray = [{
"id": "name",
"type": "string"
},
{
"id": "birthday",
"type": "date"
}
]
console.log(
dataArray.reduce((acc, curr) => {
acc[curr.id] = curr.type;
return acc;
}, {})
);
Solution 3:[3]
Is this what you're trying to achieve?
const dataArray = [
{ "id": "name", "type": "string" },
{ "id": "birthday", "type": "date" }
]
console.log(dataArray.reduce((acc, obj, i) => {
const key = obj.id;
const value = obj.type;
acc[key] = value;
return acc;
}, {}))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonathan Stellwag |
| Solution 2 | Parvesh Kumar |
| Solution 3 | Parvesh Kumar |
