'Get the value of an object from the value of another key

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



Solution 1:[1]

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);

Solution 2:[2]

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];
  .
  .
  .
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohìt Jíndal
Solution 2 Sourbh Gupta