问题
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
So the data's first row contains the attribute names of the object, How can I use that to be DRY
i.e. I hoped for
const obj = data.slice(1).map((titles) => ({ titles }) )
or similar
So this works, but I miss one more step:
const data = [
["fruits","frozen","fresh","rotten"],
["apples",884,494,494],
["oranges",4848,494,4949],
["kiwi",848,33,33]
]
const titles = data[0]; // not used below but I want to use it
const obj = data.slice(1).map(([fruits,frozen,fresh,rotten]) => ({ fruits,frozen,fresh,rotten }) )
console.log(obj)
回答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; }
回答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]
]
const zip =
keys =>
values =>
Object.fromEntries
( keys.map((k, i) => [k, values[i]])
);
const from_csv =
([titles, ...rows]) =>
rows.map(zip(titles));
console.log(
from_csv(data)
);
回答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)
回答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);
来源:https://stackoverflow.com/questions/62197270/destruct-using-titles