【问题标题】:I want print array value multiple times我想多次打印数组值
【发布时间】:2020-10-04 16:06:16
【问题描述】:
{
  "ID": 0,
  "OrganizationId": "{{OrgID}}",
  "Name":"{{TagName}}",
  "Type": 1,
  "AppliesTo": 1,
  "Values": [{"Id":1,"Text":"Level1","HODEmail":"","IsDeleted":false}]
}

在上面的 JSON 中,我想打印值数组最多一百次,其中 Id 和 Text 字段值应该每次都增加/唯一。

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow。到目前为止,您尝试过什么?
  • 预期输出是多少?什么是“唯一性”逻辑?你目前的尝试是什么?

标签: javascript postman


【解决方案1】:

此解决方案使用 while 循环和 Object.assign() 方法将项目动态添加到空的 obj.Values 数组中:

// Defines simplified object and template for array items
const obj = { ID: 0, Values: [] }
const defaultItem = { Id: 1, Text : "Level1" , HODEmail : "" }

// Starts counter at 0
let i = 0;

// iterates until counter exceeds 100
while(++i <= 100){

  // Creates next item to add to Values array
  const nextItem = Object.assign(

    {},                          // Starts with an empty object
    defaultItem,                 // Gives it all the properties of `defaultItem`
    { Id: i, Text: `Level${i}` } // Overwrites the `Id` and `Text` properties
  );

  // Adds the newly creates item to obj.Values
  obj.Values.push(nextItem);
}

// Prints the resulting object
console.log(obj);

【讨论】:

    【解决方案2】:

    您的问题中最困难的部分是您希望 id 和文本字段值增加/唯一。不确定 unique 是什么意思,但我们可以通过 sorting 我们的数组实现我们想要的。

    首先,我们将 JSON 解析为一个对象,然后对 Values 数组进行排序,然后以所需的顺序打印 Values 中的项目

    let o = JSON.parse(`{ "ID": 0, "OrganizationId": "{{OrgID}}", "Name":"{{TagName}}", "Type": 1, "AppliesTo": 1, "Values": [{"Id":1,"Text":"Level1","HODEmail":"","IsDeleted":false}] }`);
    
    
    let sorted = o.Values.sort((a,b) => {
        // simply return the element (a or b) that should come first
        return a.Id < b.Id // can also factor in uniqueness here
    })
    
    for (let j = 0; j < sorted.length && j < 100; j++) {
        console.log(sorted[j])
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2019-09-10
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多