I am creating an object
with values from an api response
. Is there a neater way to do this?
My code:
const variables = {
name: result.data.data.table.name,
org: the_org,
val1: result.data.data.table.val1,
val2: result.data.data.table.val2,
val3: result.data.data.table.val3,
val4: result.data.data.table.val4,
val5: result.data.data.table.val5,
val6: result.data.data.table.val6,
val7: new_vals7,
};
Some values come from an api call
and some are not. Was just wondering is there is a neater way to do this?
3
Answers
If you need all data from the response and overwrite some values in it this could look nice:
If you need only specific values:
You can use the spread operator to include extra entries from another object. Object.fromEntries produces that object by mapping from the numbers 1 through 6 to properties of the table object from the result.
you can try using
reduce
by keeping a list of the fields you want to extract. for the accumulator you can pass an object with the rest of the propertiesas Andy mentioned in the comment creating a new object in each iteration can be inefficient. you can avoid that by removing spread syntax.