Home > other >  Why am I getting an "Cannot read property '0' of undefined" for an array where t
Why am I getting an "Cannot read property '0' of undefined" for an array where t

Time:11-14

I am writing a piece of code to accept an array containing several objects with the properties "category", "itemName", and "Onsale" and then reorganize it into an object that takes the items in the "category" property and makes them into properties containing values from the "itemNames" property with an additional ($) added next to the value if the "onSale" property in the object it was listed in was true. After writing and testing the code it kept returning the "Cannot read property '0' of undefined" at line 13 where I was trying to call an the the [i] object in an array. My array is defined at that index value so I am not sure what is going on. I apologize if My code looks amateurish I am new to javascript. Any help would be greatly appreciated.

I tried to split up the assignment; for example instead of:

myObj = items[i]["category"][0]; 

I wrote:

myObj = items[i]["category"][0];
myObj.item[i] = ["category"][0]; 

I tried to switch my initial conditions for my for loop; for example to i = 1 instead of i = 0

I tried inputing a different array such as: myArray = [1, 2, 3, 5] but I ended up getting the same error but in a different location

Here is my code:

function organizeItems(items) {
  let myObj = {}
  for (let i = 0; i < items.length; i  ) {
    if (items[i]["category"][0] in myObj === false) {
      if (items[i]["onSale"] === true) {
        myObj = items[i]["category"][0];
        myObj.items[i]["category"][0] = [];
        myObj.items[i]["category"][0].push(items[i]["itemName"][0]   '($)');
      }
      else {
        myObj = items[i]["category"][0];
        myObj.items[i]["category"][0] = [];
        myObj.items[i]["category"][0].push(items[i]["itemName"][0]);
      }
    }
    else {
      if (items[i]["onSale"] === true) {
        myObj.items[i]["category"][0].push(items[i]["itemName"][0]   '($)');
      }
      else {
        myObj.items[i]["category"][0].push(items[i]["itemName"][0]);
      }
    }
  }
  console.log(myObj);
  return myObj;

}
var iten = [1, 2, 3, 4, 5, 6];
var itemData = [
  { category: 'fruit', itemName: 'apple', onSale: false },
  { category: 'canned', itemName: 'beans', onSale: false },
  { category: 'canned', itemName: 'corn', onSale: true },
  { category: 'frozen', itemName: 'pizza', onSale: false },
  { category: 'fruit', itemName: 'melon', onSale: true },
  { category: 'canned', itemName: 'soup', onSale: false },
];

organizeItems(itemData);

And here is the error I received:

/usr/src/app/test/unit_tests_spec.js:19
    myObj.items[i]["category"][0] = [];
                ^

TypeError: Cannot read property '0' of undefined
    at organizeItems (/usr/src/app/test/unit_tests_spec.js:20:12)
    at Object.<anonymous> (/usr/src/app/test/unit_tests_spec.js:47:1)
    at Module._compile (module.js:653:30)
    at loader (/usr/src/app/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/usr/src/app/node_modules/babel- register/lib/node.js:154:7)  
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at /usr/src/app/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/usr/src/app/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/usr/src/app/node_modules/mocha/lib/mocha.js:514:10)
    at Object.<anonymous> (/usr/src/app/node_modules/mocha/bin/_mocha:480:18)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3
npm ERR! Test failed.  See above for more details.

CodePudding user response:

Try this,

function organizeItems(items) {
  let myObj_arr = [];
  for (let i = 0; i < items.length; i  ) {
    if (items[i]["onSale"] === true) {
      myObj_arr.push({"itemName": items[i]["category"]});
    }
  }
  console.log(myObj_arr);
  return myObj_arr;
}
var iten = [1, 2, 3, 4, 5, 6];
var itemData = [
  { category: 'fruit', itemName: 'apple', onSale: false },
  { category: 'canned', itemName: 'beans', onSale: false },
  { category: 'canned', itemName: 'corn', onSale: true },
  { category: 'frozen', itemName: 'pizza', onSale: false },
  { category: 'fruit', itemName: 'melon', onSale: true },
  { category: 'canned', itemName: 'soup', onSale: false },
];

organizeItems(itemData);

CodePudding user response:

I Solved your problem.

Explain
items[i]["category"][0]'s value letters first character.
So, If you want put category letters on myObj.
mbObj.items[i]["category"][0] is not correctly syntax.
myObj[items[i]["category"][0]] is correctly.
If you want category's full letter. not first character.
myObj[items[i]["category"]] = []; < this code means => myObj = { [items[i]["category"]] : []}

If you want easy to paste .
https://bokboot.net/read?id=48&key=44426bed-78e6-49b0-80c1-9d8a13410523

function organizeItems(items) {
    let myObj = {}
    for(let i = 0; i < items.length; i  ) {
            if(items[i]["category"] in myObj === false) {
                if(items[i]["onSale"] === true) {
                    myObj[items[i]["category"]] = [];
                    myObj[items[i]["category"]].push(items[i]["itemName"]   '($)');
                }
                else {
                    myObj[items[i]["category"]] = [];
                    myObj[items[i]["category"]].push(items[i]["itemName"]);
                }
             }
             else {
                 if(items[i]["onSale"] === true) {
                     myObj[items[i]["category"]].push(items[i]["itemName"]   '($)');
                 }
                 else {
                     myObj[items[i]["category"]].push(items[i]["itemName"]);
                 }
             }
}
console.log(myObj);    
return myObj;  
    
}
var iten = [1,2,3,4,5,6];
var itemData = [
{ category: 'fruit',  itemName: 'apple', onSale: false },
{ category: 'canned', itemName: 'beans', onSale: false },
{ category: 'canned', itemName: 'corn',  onSale: true  },
{ category: 'frozen', itemName: 'pizza', onSale: false },
{ category: 'fruit',  itemName: 'melon', onSale: true  },
{ category: 'canned', itemName: 'soup',  onSale: false },
 ];

organizeItems(itemData);

CodePudding user response:

You likely sent your function an items array that was never instantiated. Try logging items to the console prior to let myObject = {} and you may find the items is undefined, in order to prove my suspicion.

  • Related