I would like to know how modify array of objects in javascript.
i.e for obj change the value key array to string when value is array
change the value key string to array when value is string
also, how to convert output as input obj and (vice-versa-<input as output) in javascript
function newObject(obj){
var result = obj.map(e=>typeof e.value === "string" ?
{...e, value: [e.value] } :
e.value.map(value => ({...e,value}))
).flat()
console.log(result);
return result;
}
scenario1
input:
obj =[
{ id: 0, key: "s1", value: ["listA","listB"], img:"" },
{ id: 1, key: "s2", value: ["listC"], img: "" },
{ id: 2, key: "s3", value: ["listD","listE","listF"], img: "" }
]
Expected output:
[
{ id: 0, key: "s1", value: "listA,listB", img:""},
{ id: 1, key: "s2", value: "listC", img:""},
{ id: 2, key: "s3", value: "listD,listE,listF", img:""}
]
scenario 2
input
[
{ id: 0, key: "s1", value: "listA,listB", img:""},
{ id: 1, key: "s2", value: "listC", img:""},
{ id: 2, key: "s3", value: "listD,listE,listF", img:""}
]
Expected Output
[
{ id: 0, key: "s1", value: ["listA","listB"], img:"" },
{ id: 1, key: "s2", value: ["listC"], img: "" },
{ id: 2, key: "s3", value: ["listD","listE","listF"], img: "" }
]
listFin the last object of your output array? (first code block?)arr.forEach(item => item.value = item.value.join('')andarr.forEach(item => item.value = item.value.split(',')