0

I have stored data in local storage in an array. Now I want to remove certain item from that array present in local storage. For that first I have

var items = JSON.parse(localStorage.getItem('shoppingCart'));
var resturantid = localStorage.getItem('resturant_id');
var filtered = [];
for (var q = 0; q < items.length; q++) {

  if (items[q].resturantid == resturantid) {
    filtered.push(items[q]);
  }
}
console.log(typeof filtered, filtered);

output is OBJECT

in console

(2) [{…}, {…}]
0: {name: "veg-momo", price: 12, count: 8, resturant: "Test Developer", resturantid: 2, …}
1: {name: "afdafasdf", price: 123, count: 4, resturant: "Test Developer", resturantid: 2, …}
length: 2
__proto__: Array(0)

typeof gives me object and because of this I haven't been able to use map function as it says array.map is not a function. I want these things to happen just to remove certain item in local storage key in which array is set.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
ram ram
  • 27
  • 5

3 Answers3

0

Your object is something like {0: {…}, 1: {…}} you need to make an array of values like [{...}, {...}]! To do so use Object.values() and then apply map() or filter() or reduce() as per your program needs.

let obj = Object.assign({},[{name: "veg-momo", price: 12, count: 8, resturant: "Test Developer", resturantid: 2}, {name: "afdafasdf", price: 123, count: 4, resturant: "Test Developer", resturantid: 2}]);

// obj.map(x => {console.log(x)}); //error: Uncaught TypeError: obj.map is not a function

Object.values(obj).map(x => console.log(x)); // Works!
Arun Saini
  • 6,714
  • 1
  • 19
  • 22
-1

The problem is that you have to use filtered[0].name etc Because in HTML there is no object so you have to use this

But if you want to display in HTML you can use filtered[0].toString() And print it

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Lonely
  • 66
  • 7
  • Please read [answer] for information on how to answer. Feel free to browse the other articles in the [help] to familiarize yourself with the site and how it works before using it. – Heretic Monkey Jul 13 '20 at 18:35
-1

This isn't an appropriate use of map(); this returns a new array with elements for all the original elements. Use filter() to return only the elements that satisfy a test.

var filtered = items.filter(item => item.restaurantid == restaurantid);

Your object is an array, so all the standard array methods should work for it.

Barmar
  • 741,623
  • 53
  • 500
  • 612