Acces Array of object and accesing or checking ut

Viewed 21

So i tried to make the program that formattting the input to be array and object, but i struggle to acces, check, and add an object to an array, here's the code, input and output

  1. The program will ask for input from the user, the request will be formatted as: { name : (inputName), location : (inputlocation), request : [ {(productName ) : (totalRequest)} e.g : {meatball : 1}, ], }
  2. The program will check whether the same item has been previously ordered by the same user
  3. If it is, then the totalRequest of the same item will be increased, if not, an object will be created with the format {productName : totalRequest }
let user = {
        name : readLine.question("Name : "),
        location : readLine.question('Location : '),
        request : []
}

while(true){
    var product = readLine.question('input your request : ').toLowerCase();
    var total = readLine.question("total request : ");
    var requestProduct = {}
    //this is the part of the problem, the data is checked in here 
    for(let i of user.request){
        for(let j in i){
            if(j == product){
                i[product] += total;
            } else {
                requestProduct[product] = total;
                user.request.push(requestProduct);
            }
        }
    }
    var isEnough = readLine.question('Enough ?(yes/no)');
    if(isEnough == 'yes'){
        console.log(user);
        break;
    } else {
        continue;
    }
}

/** 
 * expected output :
 * {
 * name : Budi,
 * Location : Supeno Street, number 150,
 * request : [
 *          {meatball : 12},
 *          {"ice tea" : 12},
 *      ]
 * }
 * output on reality: 
 * {
 * name : Budi,
 * Location : Supeno Street, number 150,
 * request : []
 * }
 * */ 

i've commented the problem part on the code review, i hope someone can help me solve the problem

1 Answers

You shouldn't loop through the object. Use Object.keys() to get the key of the object. Then you can check if this key matches what the user entered.

let found = false;
for (let i of user.request) {
  let key = Object.keys(i)[0];
  if (key == product) {
    found = true;
    i[key] += total;
    break;
  }
}

if (!found) {
  user.request.push({[product]: total});
}

Related