Destruct Using Titles
I have answered a few questions using destructing, I just want to take this one to the next level I want to not use reduce in this example but pure destructing if at all possible S
Solution 1:
You could map the entries for an object.
const
data = [["fruits", "frozen", "fresh", "rotten"], ["apples", 884, 494, 494], ["oranges", 4848, 494, 4949], ["kiwi", 848, 33, 33]],
mapWith = keys =>values =>Object.fromEntries(keys.map((k, i) => [k, values[i]])),
getArray = ([keys, ...data]) => data.map(mapWith(keys)),
array = getArray(data);
console.log(array);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Old simpler example
const data = [
["fruits", "frozen", "fresh", "rotten"],
["apples", 884, 494, 494],
["oranges", 4848, 494, 4949],
["kiwi", 848, 33, 33]
]
const titles = data[0];
const obj = data.slice(1).map(
arr =>Object.fromEntries(
titles.map(
(t, i) => [t, arr[i]]
)
)
);
console.log(obj);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 2:
You can create a curried version of zip
which is similar to Object.fromEntries
except that it doesn't take pairs but a list of keys and a list of values and pairs are formed based on indexes:
zip(['a','b'], [1,2]);
//=> {a: 1, b: 2})
Because it is curried you can use it in your map and avoid hardcoding titles:
const data = [
["fruits","frozen","fresh","rotten"],
["apples",884,494,494],
["oranges",4848,494,4949],
["kiwi",848,33,33]
]
constzip =
keys =>
values =>Object.fromEntries
( keys.map((k, i) => [k, values[i]])
);
constfrom_csv =
([titles, ...rows]) =>
rows.map(zip(titles));
console.log(
from_csv(data)
);
Solution 3:
You could use reduce
, but you can't really destruct...
const data = [
["fruits","frozen","fresh","rotten"],
["apples",884,494,494],
["oranges",4848,494,4949],
["kiwi",848,33,33]
]
const titles = data[0];
const obj = data.slice(1).map((row) => titles.reduce((agg, cur, index) => {
agg[cur] = row[index];
return agg;
}, {}));
console.log(obj)
Solution 4:
const data = [
["fruits","frozen","fresh","rotten"],
["apples",884,494,494],
["oranges",4848,494,4949],
["kiwi",848,33,33]
];
const [titles, ...rest] = data;
const obj = rest.map((xs) => {
const o = {};
xs.forEach((x,i) => o[titles[i]] = x);
return o;
});
console.log(obj);
Post a Comment for "Destruct Using Titles"