简体   繁体   中英

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.

This solution uses a while loop and the Object.assign() method to dynamically add items to an empty obj.Values array:

 // 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. Not sure what unique means, but we can achieve what we want by sorting our array.

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

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])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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