Mahir Altınkaya
Mahir Altınkaya

Reputation: 439

Convert String to Object Key Name

I'm sending different objects to a component outside, and component data varies depending on objects. I'm getting the names with the Object.key function because the keywords I send have different key. Then I want to sort by the key. For this I need to define the name I received with Object.key function. How can I do it?

 upSortTable(items, val) {
  //items = Object,
  //val = index
  let Keys = Object.keys(items[0]); // ["item_id","item_title"]
  let keyname = Keys[val]; //item_id String value
  //want to use in sort function as b.item_id
  return items.sort(function(a, b) {
    return b.keyname - a.keyname;
  });
},

Upvotes: 1

Views: 655

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85643

You'll need to use computed property:

return items.sort(function(a, b) {
  return b[keyname] - a[keyname];
});

When you do a.keyname you're actually looking for the property keyname in a itself.

Upvotes: 3

Related Questions