如何从给定的JSON模式中获取新的JSON模式,只有一个键值对从"属性"中随机选择。属性。它还应该有"标题"和"键入"属性。
AuthenticationEvents::AUTHENTICATION_SUCCESS
答案 0 :(得分:0)
首先,您可以获得0-4之间的随机数,可用于随机获取properties
密钥,并使用该密钥将其添加到新JSON对象的properties
中:
var jsonSchema = { "title": "animals object",
"type": "object",
"properties":
{
'cat': 'meow',
'dog': 'woof',
'cow': 'moo',
'sheep': 'baaah',
'bird': 'tweet'
}
};
var newJSON = { "title": "animals object",
"type": "object",
"properties":{}
};
var randomNumber = Math.floor(Math.random() * 5);
var randomPropertyKey = Object.keys(jsonSchema.properties)[randomNumber];
newJSON.properties[randomPropertyKey] = jsonSchema.properties[randomPropertyKey];
console.log(newJSON);
答案 1 :(得分:0)
这应该可以解决问题:
var originalJson = {
"title": "animals object",
"type": "object",
"properties": {
'cat': 'meow',
'dog': 'woof',
'cow': 'moo',
'sheep': 'baaah',
'bird': 'tweet'
}
};
// deep copy of the json object
var jsonCopy = JSON.parse(JSON.stringify(originalJson));
//gets a random property of a collection
var propToKeep = pickRandomProperty(jsonCopy.properties);
//deletes all properties of the copied collection except the randomly chosen one
for (var key in jsonCopy.properties) {
if(key.toString() !== propToKeep) {
delete jsonCopy.properties[key]
}
}
function pickRandomProperty(obj) {
var result;
var count = 0;
for (var key in obj){
//if there's only one left, take it.
if (Math.random() < 1 / ++count){
result = key;
}
}
return result;
}
console.log("copy", jsonCopy);
console.log("original", originalJson);