从Object中选取一些随机属性

时间:2015-07-06 07:47:32

标签: javascript object random properties

如果我有以下几个对象:

var points = {'p1':{x:1,y:1,z:2}, 'p2':{x:2,y:1,z:4},.....,'p10':{x:3,y:2:z:2}};
var lines = {'l1':{....},'l2':{....},......,'l10'{....}};
var jsonObject = {'info': 'information', 'points': points, 'lines': lines};

如何从相应对象中选择(例如,3个随机点和3个随机行)并在jsonObject中更新,以便新jsonObject现在包含{'info': 'information', 'points': pointObj, 'lines': lineObj};其中{{1}包含来自orighinal pointObj对象的3个随机点,points包含来自原始lineObj对象的3个随机行?

3 个答案:

答案 0 :(得分:1)

作为带键的对象,您可以使用Object.keys将其所有键作为数组获取:

var getRandoms = function(source, number) {
  var keys = Object.keys(source) // get all keys as array
      ,len = keys.length;        // keys count

  var result = {};

  // not enough points, so just return all object from source.
  if (len < number) {
    return source;
  }
  var rand, key, count = 0;
  while (count < number) {
    rand = Math.floor(Math.random() * len);
    key = keys[rand];
    result[key] = source[key];
    // Remove used key
    keys.splice(rand, 1);
    --len;
    ++count;
  }

  return result;
}

jsonObject.points = getRandoms(points, 3);
jsonObject.lines = getRandoms(lines, 3);

答案 1 :(得分:0)

使用random()功能。

var randomNum = Math.floor((Math.random() * 10));

现在基于randomNum选择一个使用它的索引。

var jsonObject = {
    "points" : [],
    "lines" : []   
};
var count = 0;
while(count <3)
{
var randomNum = Math.floor((Math.random() * 10))
jsonObject["points"].push(points[randomNum][0]);

randomNum = Math.floor((Math.random() * 10));
jsonObject["lines"].push(lines[randomNum][0]); 
count++;
}

答案 2 :(得分:0)

创建一个函数,在[0-10]之间返回随机选择的数字

&#13;
&#13;
function get3RandomPoint(){
  var temp, arr=[];
   while(arr.length < 3) {
     temp = Math.ceil(Math.random()*10);
     if(arr.indexOf(temp) === -1) {
      arr.push(temp);
     }
    }
  return arr;
 }


var points = {'p1':{x:1,y:1,z:2}, 'p2':{x:2,y:1,z:4},.....,'p10':{x:3,y:2:z:2}};
var lines = {'l1':{....},'l2':{....},......,'l10'{....}};

var randomNums = get3RandomPoint();
var randomPoints = {p1: points["p"+ randomNums[0]], p2: points["p"+ randomNums[1]], p2: points["p"+ randomNums[2]]};

randomNums = get3RandomPoint();
var randomLiness = {l1: points["l"+ randomNums[0]], l2: points["l"+ randomNums[1]], l2: points["l"+ randomNums[2]]};

var jsonObject = {'info': 'information', 'points': randomPoints, 'lines': randomLiness};

console.log(jsonObject);
&#13;
&#13;
&#13;