0

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?

4
  • stackoverflow.com/questions/41585611/… may be helpful. Commented Aug 24, 2018 at 4:45
  • 1
    map returns an array. 0 and 1 are indices of that array. You're trying to create an object with keys nm only? That's simply not possible because object cannot contain duplicate keys. Please define your problem clearly. Commented Aug 24, 2018 at 4:48
  • nm is variable containing different strings.. It depends of $(li).find('td.h-text-left.over-s-only').text(); I have edited example objects Commented Aug 24, 2018 at 4:53
  • Please accept the answer, which helped you best. SO questions should have an accepted answer. Thx Commented Feb 4, 2019 at 12:32

1 Answer 1

1

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;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.