简体   繁体   English

我想多次打印数组值

[英]I want print array value multiple times

{
  "ID": 0,
  "OrganizationId": "{{OrgID}}",
  "Name":"{{TagName}}",
  "Type": 1,
  "AppliesTo": 1,
  "Values": [{"Id":1,"Text":"Level1","HODEmail":"","IsDeleted":false}]
}

In above JSON I want to print the values array up to hundred times in which Id and Text field value should be increasing/unique every time.在上面的 JSON 中,我想打印值数组多达一百次,其中 Id 和 Text 字段值应该每次都增加/唯一。

This solution uses a while loop and the Object.assign() method to dynamically add items to an empty obj.Values array:此解决方案使用 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);

The most difficult part of your question is that you want the id and text field value to be increasing / unique.您的问题中最困难的部分是您希望 id 和 text 字段值增加/唯一。 Not sure what unique means, but we can achieve what we want by sorting our array.不确定唯一是什么意思,但我们可以通过对数组进行sorting来实现我们想要的。

First, we'll parse the JSON into an object, then we'll sort the Values array, then we'll print the items in Values in the desired order首先,我们将 JSON 解析为 object,然后对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])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM