如何循环遍历一个对象形成形成条件

我有一个对象,如下所示:


{

    Condition0: "5"

    Condition1: "6"

    LogicalOperator0: "&&"

    Operator0: "<"

    Operator1: "!="

    Question0: "How do you rate our services?"

    Question1: "How likely are you to recommend our services to others?"

}

我想安排它形成一个条件


Question0 Operator0 Condition0 LogicalOperator0 Question1 Operator1 Condition1 

因此结果形成如下所示的比较运算符:


How do you rate our services? < 5 && How likely are you to recommend our services to others? != 6

任何人都请协助在 JS 中实现这一目标。


回首忆惘然
浏览 77回答 3
3回答

GCT1015

您可以为属性和数字部分采用嵌套循环,并将所有部分收集在一个数组中。let data = { Condition0: "5", Condition1: "6", LogicalOperator0: "&&", Operator0: "<", Operator1: "!=", Question0: "How do you rate our services?", Question1: "How likely are you to recommend our services to others?" },&nbsp; &nbsp; keys = ['Question', 'Operator', 'Condition', 'LogicalOperator'],&nbsp; &nbsp; result = [],&nbsp; &nbsp; i = 0;outer: while (true) {&nbsp; &nbsp; for (const part of keys) {&nbsp; &nbsp; &nbsp; &nbsp; const key = `${part}${i}`;&nbsp; &nbsp; &nbsp; &nbsp; if (!(key in data)) break outer;&nbsp; &nbsp; &nbsp; &nbsp; result.push(data[key]);&nbsp; &nbsp; }&nbsp; &nbsp; i++;}console.log(result.join(' '));

当年话下

将对象分配给变量并从那里访问它:var someName = {&nbsp; &nbsp; Condition0: "5"&nbsp; &nbsp; Condition1: "6"&nbsp; &nbsp; LogicalOperator0: "&&"&nbsp; &nbsp; Operator0: "<"&nbsp; &nbsp; Operator1: "!="&nbsp; &nbsp; Question0: "How do you rate our services?"&nbsp; &nbsp; Question1: "How likely are you to recommend our services to others?"}//Accessing the values would look like://someName.question0 + somename.operator0 + somename.condition0...如果您遍历该对象,则只能按照创建它的顺序访问它。您似乎需要以不同的顺序访问它。

蛊毒传说

您可以将显示属性的顺序存储到一个数组中并操作该数组const obj = {&nbsp; Condition0: '5',&nbsp; Condition1: '6',&nbsp; LogicalOperator0: '&&',&nbsp; Operator0: '<',&nbsp; Operator1: '!=',&nbsp; Question0: 'How do you rate our services?',&nbsp; Question1: 'How likely are you to recommend our services to others?'}const order = [&nbsp; 'Question0',&nbsp; 'Operator0',&nbsp; 'Condition0',&nbsp; 'LogicalOperator0',&nbsp; 'Question1',&nbsp; 'Operator1',&nbsp; 'Condition1']const res = order.map(prop => obj[prop]).join(' ')console.log(res)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript