我想要多次打印数组值


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

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

此解决方案使用 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);

问题中最困难的部分是您希望 id 和文本字段值增加/唯一。不确定独特意味着什么,但我们可以通过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])
}

最新更新