json 对象数组的笛卡尔积
我如何在对象的数组中产生所有值的所有组合。
var input = [
{ "colour" : "red",
"material" : "cotton" ,
"shape" : "round"
},
{ "colour" : "green",
"material" : "wool" ,
"shape" : "square"
}
];
预期的输出是所有可用选项的笛卡尔产品,创建了带有相同键的新数组。
var expected = [
{ 'colour': 'red', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'red', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'square' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'square' }
];
How can I produce all of the combinations of the values in an array of the of Objects.
var input = [
{ "colour" : "red",
"material" : "cotton" ,
"shape" : "round"
},
{ "colour" : "green",
"material" : "wool" ,
"shape" : "square"
}
];
The expected output is the Cartesian product of all the options available, creating a new array with the same keys.
var expected = [
{ 'colour': 'red', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'red', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'square' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'square' }
];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将分两个步骤:
步骤1:收集每个键的所有值,
这将给出
步骤2:通过使用三重嵌套的迭代创建笛卡尔产品:
它给出
I would approach this in two steps:
Step 1: collect all values for each key
Which will give
Step 2: Create the cartesian product by using a triple-nested iteration:
Which gives