gpt4 book ai didi

javascript - 如何将数组中的 true 和 false 字符串解析为 boolean 值

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

如何将数组中的 truefalse 字符串解析为 Javascript 中的 boolean 值?

例如,

来自:

{"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":"false","static":"false","widget":"Photo"}

到:

{"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":false,"static":false,"widget":"Photo"}

movedstatic 的值必须是 boolean 值,但它们显示为字符串。有没有办法只更改这些值?

这是我获取数组的函数:

loadData = () => {

let dashboardId = 1;

return axios
.get('api/dashboards/' + dashboardId)
.then(result => {

//@TODO Parse true and false strings to become booleans

console.log(result);
this.setState({
items: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
})
.catch(error => {
console.log(JSON.stringify(this.state.items));
console.error('error: ', error);
})
};

最佳答案

parse the true and false strings in an array to become boolean

你说数组中的字符串?使用 Array.map()

进行迭代

const items = ["true", "false", "something else"]

const booleans = items.map(boolFromStringOtherwiseNull)
console.log({items, booleans}) // show result

function boolFromStringOtherwiseNull(s) {
if (s == 'true') return true
if (s == 'false') return false
return null
}

对象?使用 Object.values()

进行迭代

const data = {"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":"false","static":"false","widget":"Photo"};

const booleans = Object.values(data).map(boolFromStringOtherwiseNull); // convert
console.log({data, booleans}); // show result

function boolFromStringOtherwiseNull(s) {
if (s == 'true') return true
if (s == 'false') return false
return null
}

转换 boolean 字符串,并保持原始对象的结构?

const data = {"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":"false","static":"false","widget":"Photo"}

const result = Object.entries(data)
.map(boolFromStringOtherwiseNoOp) // convert 'boolean strings' to boolean
.reduce(gatherObjectFromEntries, {}) // collect all entries into 1 object

console.log({data, result}); // result is an object where non-boolean-strings are untouched.

function boolFromStringOtherwiseNoOp([key, value]) {
if (value == 'true') return [key, true]
if (value == 'false') return [key, false]
return [key, value]
}

function gatherObjectFromEntries(accumulation, [key, value]) {
accumulation[key] = value
return accumulation
}

希望这对您有所帮助。干杯,

关于javascript - 如何将数组中的 true 和 false 字符串解析为 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947238/

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