Home > front end >  How to get the key and value not overwritten inside a for loop in an object?
How to get the key and value not overwritten inside a for loop in an object?

Time:12-09

I have this function that takes two lists as arguments. The first letter of each element of the list "L" is the identification of a book category. For example, "BKWR" and "BTSQ" are same category books because they start with the same letter "B". The positive integer separated by space is the number of books in that category. Now what the function does is that it takes the first list and matches from the second list whether the book category starting with the letter is present or not. If it is present then it sums the number. For example in the list "L" two book categories starting with "B" are present so it is supposed to sum them.

However, rather than summing the two, my function is overwriting the value of the previous "B" category. How can I stop it from overwriting the value?

function extract(list,stocklist){
  let newArr = [];
  for (let i = 0; i < stocklist.length; i  ){
    for (let j = 0; j < list.length; j  ){
      if (stocklist[i] == list[j][0]){
        newArr.push(list[j]);
      }
    }
  }
  let selected = newArr.map((item) => item.split(' '));
  let extracted = {};
  for (let k = 0; k < selected.length; k  ){
    for (let l = 0; l < selected[k].length-1; l  ){
        let key = selected[k][l][0];
        let value = selected[k][l 1];
        extracted[key] =  value;
    }
  }
  
  return extracted;
}

let L = ["ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"];
let M = ["A", "B", "W"];

console.log(extract(L,M));

CodePudding user response:

If there's already a value for the key, add to it instead of overwriting it. So change

extracted[key] =  value;

to

if (key in extracted) {
    extracted[key]  = parseInt(value);
} else {
    extracted[key] = parseInt(value);
}

CodePudding user response:

You actually need to add the "value" to your extracted object:

function extract(list,stocklist){
  let newArr = [];
  for (let i = 0; i < stocklist.length; i  ){
    for (let j = 0; j < list.length; j  ){
      if (stocklist[i] == list[j][0]){
        newArr.push(list[j]);
      }
    }
  }
  let selected = newArr.map((item) => item.split(' '));
  let extracted = {};
  for (let k = 0; k < selected.length; k  ){
    for (let l = 0; l < selected[k].length-1; l  ){
        let key = selected[k][l][0];
        let value = selected[k][l 1];
        if(value) {
         extracted[key] = ( extracted[key] || 0)    value;
       }
    }
  }
  
  return extracted;
}

let L = ["ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"];
let M = ["A", "B", "W"];

console.log(extract(L,M));

CodePudding user response:

Here's the minor part you are missing. Check the key and sum up, or simply assign the first value like:

extracted[key] = extracted[key] ? extracted[key]   Number(value) : Number(value);
  • Related