JavaScript-从字符串变量获取数组对象 [英] JavaScript - Get an array object from a string variable

查看:45
本文介绍了JavaScript-从字符串变量获取数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var list = "OVER_30 = true || NUM_OF_JACKETS >=3 || COUNT_TOTAL == 500";
var array = getList(); // array[0].OVER_30 = true, array[0].NUM_OF_JACKETS = 5, array[0].COUNT_TOTAL = 500;

if (array[0].OVER_30 = true || array[0].NUM_OF_JACKETS >=3 || array[0].COUNT_TOTAL == 500) { <--- What I want to accomplish
   return true;
}

我有一个名为 list 的字符串变量,其中包含条件.如何在每个条件前面添加 array [0].来组合数组和字符串?

I have a string variable called list that contains the conditions. How can I add array[0]. in front of each condition to combine the array and string?

var format = array [0].+条件?

var format = array[0]. + condition??

推荐答案

我只能为您找到eval

I could only find eval for you

您需要确保语句的格式正确,并带有空格和正确数量的 =

You DO need to make sure the statements are correctly formatted with spaces and correct number of =

因此,在这里我使用两个地图和一个 some -如果您有&&代替||您需要每一个,它们将返回一个组合结果,表示[true,true,true]为true,其他任何组合均为false

So here I use two maps and a some - if you have && instead of || you need every which will return one combined result, meaning [true,true,true] is true and any other combination is false

使用 some 将返回一个组合结果,任何true为true

Using some will return one combined result, any true is true

const list = "OVER_30 === true || NUM_OF_JACKETS >= 3 || COUNT_TOTAL === 500";

const array = [
{ OVER_30 : true, NUM_OF_JACKETS : 5, COUNT_TOTAL : 500},
{ OVER_30: false, NUM_OF_JACKETS: 2, COUNT_TOTAL: 400 },
{ OVER_30: true, NUM_OF_JACKETS: 2, COUNT_TOTAL: 400 }
]

const tests = list.split("||");

const results = array.map(item => tests.map(test => {
    const [name, oper, val] = test.trim().split(" ");
    const statement = `${item[name]} ${oper} ${val}`
    return eval(statement)
  }).some(test => test)
)
console.log(results)

这篇关于JavaScript-从字符串变量获取数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆