简体   繁体   中英

How to map an Array to an Object in Javascript?

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?

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;
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM