Reputation: 119
I'm using array.map to iterate through DOM elements in nodejs/cheerio.
There is my code:
const $ = cheerio.load(html);
const lis = $("table[id*='sortable-']").find('tr');
const lisy = lis.map((i, li) => {
var name = $(li).find('td.h-text-left.over-s-only').text();
var cnt = $(li).text();
return {
content: cnt
}
}).get();
And now, I want to return named objects by "name" variable, but for now, .map returning iterated objects:
0: {"cnt": content}, 1: {"cnt": content}
Insted of this, I want to get objects indexed by every "name" like this:
name: {"cnt": content}, name: {"cnt": content}
Is it possible to name returned object like this?
Upvotes: 0
Views: 120
Reputation: 4005
You can achieve your goal by using Array.prototype.reduce
var result = lis.reduce(function(map, li) {
var name = $(li).find('td.h-text-left.over-s-only').text();
var cnt = $(li).text();
map[name] = { content: cnt };
return map;
}, {});
Upvotes: 1