Javascript 如何覆盖json对象?
我有一个json对象,它有一个名为favorite的键,它的值为true,当按下按钮时,我想将favorite键的值覆盖为false,反之亦然 这是json对象内部的内容:Javascript 如何覆盖json对象?,javascript,Javascript,我有一个json对象,它有一个名为favorite的键,它的值为true,当按下按钮时,我想将favorite键的值覆盖为false,反之亦然 这是json对象内部的内容: allPlaces: "[{"title":"Test1 ","description":"Test 2","category":"restaurant","favourite"
allPlaces: "[{"title":"Test1 ","description":"Test 2","category":"restaurant","favourite":false}]"
allPlaces
是一个数组(在本例中,它有1个项),因此为了更改其中对象的属性,必须为其指定一个索引,如soallPlaces[0]。favorite=true
我添加了一些代码作为参考
const allPlaces='[{“title”:“Test1”,“description”:“test2”,“category”:“restaurant”,“false}];
const places=JSON.parse(allPlaces);
位置[0]。收藏夹=true;
console.log(places[0])代码>
function favourite(element) {
var allPlaces = JSON.parse(localStorage.getItem("allPlaces"));
var placeIndex = element.getAttribute("data");
places = {allPlaces}
if (allPlaces["favourite"] == true) {
places.favourite[placeIndex] = false;
element.querySelector('ion-icon').setAttribute('name', 'star-outline');
} else {
console.log("working");
places.favourite[placeIndex] = true;
element.style.color = '#FFE234';
element.querySelector('ion-icon').setAttribute('name', 'star');
}
localStorage.setItem("allPlaces", JSON.stringify(places));
}