response.json()) .then((users) => { -6ren">
gpt4 book ai didi

javascript - 删除对象中找到的所有 "true"和 "false"周围的引号

转载 作者:行者123 更新时间:2023-11-28 16:45:28 26 4
gpt4 key购买 nike

  fetch("./files.json")
.then(response => response.json())
.then((users) => {
var files = users.find(x => typeof x[username] !== "undefined");
console.log(JSON.stringify(files);
files = files.replace(/:[ ]*"false"/,':false' ).replace( /'/g,'"');

})

上面我只是试图将所有带有引号的 "true""false" 替换为不带引号的

上述错误replace is not a function,我也尝试了map,并得到了cannot set on undefined错误。在这些尝试之前,usersfiles 控制台正常。有能力在这里做到这一点吗?

响应数据经过 JSON.stringify 后如下所示:

userMoves: [{id: "slz1", checked: "false"}, {id: "slz2", checked: "false"}, {id: "slz3", checked: "false"},…]

更新:首先将文件转换为字符串会更新第一个找到的false,但不是全部。

files = JSON.stringify( files ).replace(/:[ ]*"false"/,':false' ).replace( /'/g,'"');

最佳答案

不需要正则表达式或字符串化。

首先,我们将迭代 userMoves 数组中的对象数组,然后使用严格检查来检查 1.) 值是否为 true,2 值是否为字符串,然后我们分别分配 true 和 false

fetch("./files.json")
.then(response => response.json())
.then((users) => {
let files = users.find(x => typeof x[username] !== "undefined");
for ( let file in files.userMoves ){
if ( files[ file ].checked === "true" ) {
files[ file ][ 'checked' ] = true;
}else if ( files[ file ].checked === "false" ){
files[ file ][ 'checked' ] = false;
}
}
})

关于javascript - 删除对象中找到的所有 "true"和 "false"周围的引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60609461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com