I have below object and I can reference key e as in the following:
var obj = {
"id": 100,
"date": "2021",
"d": "D",
"e": {
"e1": "E"
},
"f": {
"f1": "F"
}}
console.log(obj.e); // returning { e1: 'E' }
I want to get the value by using the object key as below and input [Key] always be a that place.
{
"d": "D",
"e": "E",
"f": "HardCode FF"
}
Input, that I am receiving,
{"id":100,"date":"2021","d":"D","e":{"e1":"E"},"f":{"f1":"F"}}
Output, that I am expecting,
{"d":"D","e":"E","f":"HardCode"}
I tried the above approach but seems I am getting the child json obj only.
How can I do this?
We can add conditionally if you know the keys you want
const obj = { "id": 100, "date": "2021", "d": "D", "e": { "e1": "E" }, "f": { "f1": "F" } };
const newObj = {
...(obj.e && {e: obj.e.e1}),
...(obj.d && {d: obj.d}),
f: "HardCode"
}
console.log(newObj)
We can reduce
const obj = { "id": 100, "date": "2021", "d": "D", "e": { "e1": "E" }, "f": { "f1": "F" } };
const newObj = Object.entries(obj).reduce((acc,[key,val]) => {
if (key === "f") acc["f"] = "HardCode";
else if (["id","date"].includes(key)) return acc;
else if (typeof val === "object") acc[key] = Object.values(val)[0]
else acc[key]=val;
return acc;
},{})
console.log(newObj);
We can destruct
const obj = { "id": 100, "date": "2021", "d": "D", "e": { "e1": "E" }, "f": { "f1": "F" } };
const { id, date , ...newObj } = obj;
newObj.f = "HardCode"
newObj.e = newObj.e.e1; // not elegant
console.log(newObj);
To not have to code the e key, we can just get all first entries
const obj = { "id": 100, "date": "2021", "d": "D", "e": { "e1": "E" }, "f": { "f1": "F" } };
const { id, date , ...newObj } = obj;
newObj.f = "HardCode"
Object.entries(newObj).forEach(([key,val]) => { if (typeof val === "object") newObj[key] = Object.values(val)[0] })
console.log(newObj);
Alternatively use Object.assign with some filtering, but for your usecase, my code should be enough
You can destructure the object and mutate the rest, you can get the result you're expecting. Below is the code which I tried.
let obj = {"id":100,"date":"2021","d":"D","e":{"e1":"E"},"f":{"f1":"F"}};
let {id, date, ...rest} = obj;
rest.e = rest.e.e1;
rest.f = "HardCode";
console.log(rest);