Home > Software engineering >  Get the value of an object from the value of another key
Get the value of an object from the value of another key

Time:02-26

I have a Typescript project in which I have two objects. What I am doing is getting a data from the second object depending on the value of the first object.

This is the first object:

let sheet = [
  {
      desc: "work"
  },
  {
      desc: "serv"
  }
]

This is the second object:

let list = [
  {
    "properties": {
      "sheetId": 1000297558,
      "title": "work",
      "index": 0
    }
  },
  {
    "properties": {
      "sheetId": 24134863,
      "title": "serv",
      "index": 1
  }
]

What I want: Get the value of the sheetId property where the value of the title property of that object is equal to the value of the desc property of the first object

This is what I do:

let sheetId: number

for (let getSheet of sheet ) {
  for (let getList of list) {
    if (getList.properties.title == getSheet.desc) {
      sheetId = getList.properties.sheetId
      .
      .
      .
    }
  }
}

My problem: I am iterating twice, each one on an object, this when the process is large consumes a lot, I would like to know if there is another more efficient way to do this

CodePudding user response:

Convert the list to a Map of sheetId by title O(n) (where n is the length of list), and then extract the sheetId from the Map in O(1).

Basically a Map is an object the hold [key, value] pairs. You can get the value by calling the .get() method with the key. In your case, to prevent iterating the list multiple type, we can iterate it once to index the sheetId by title.

const sheet = [{"desc":"work"},{"desc":"serv"}]

const list = [{"properties":{"sheetId":1000297558,"title":"work","index":0}},{"properties":{"sheetId":24134863,"title":"serv","index":1}}]

const sheetIdByTitle = new Map(list.map(({ properties: p }) => [p.title, p.sheetId]))

console.log(sheetIdByTitle.get(sheet[0].desc))

const ids = sheet.map(o => sheetIdByTitle.get(o.desc))

console.log(ids)

CodePudding user response:

If I understand it correctly, You have both the arrays with same length and in same order. If Yes, you can try this solution.

let sheet = [{
  desc: "work"
}, {
  desc: "serv"
}];

let list = [{
  "properties": {
    "sheetId": 1000297558,
    "title": "work",
    "index": 0
  }
}, {
  "properties": {
    "sheetId": 24134863,
    "title": "serv",
    "index": 1
  }
}];

const res = list.map((obj, index) => obj.properties.title === sheet[index].desc ? obj.properties.sheetId : 'Not matched!');

console.log(res);

CodePudding user response:

You can try this variation as well.

let descToSheetIdMap = list.reduce((p, c) => {
  p[c.properties.title] = c.properties.sheetId
  return p
}, {});

for (let getSheet of sheet ) {
  sheetId = descToSheetIdMap[getSheet.desc];
  .
  .
  .
}
  • Related