[英]Cartesian product of javascript object with different types of values like string, object and array
I am working on an assignment. 我正在做作业。 I have the following object form. 我有以下对象形式。
{
name: "name here",
skills: [ "cash", "shares" ],
subjects:
[
{
subName: "subject1",
remark: ['remark1', 'remark2']
},
{
subName: "subject2",
remark: ['remark1', 'Hockey']
}
]
}
I want to generate a Cartesian product of the properties so that the output is an array of the following form: 我想生成属性的笛卡尔乘积,以便输出是以下形式的数组:
[
{ "name": "name here", "skills": "cash", "subjects": { "subName": "subject1", “remark”: “remark2” }},
{ "name": "name here", "skills": "cash", "subjects": { "subName": "subject1", “remark”: “remark1” }},
{ "name": "name here", "skills": "cash", "subjects": { "subName": "subject2", “remark”: “remark1” }},
{ "name": "name here", "skills": "cash", "subjects": { "subName": "subject2", “remark”: “Hockey” }},
{ "name": "name here", "skills": "shares", "subjects": { "subName": "subject1", “remark”: “remark1” }},
{ "name": "name here", "skills": "shares", "subjects": { "subName": "subject1", “remark”: “remark2” }},
{ "name": "name here", "skills": "shares", "subjects": { "subName": "subject2", “remark”: “remark1” }},
{ "name": "name here", "skills": "shares", "subjects": { "subName": "subject2", “remark”: “Hockey” }}
]
I have tried many of the algorithms(mentioned in other SO posts) and even tried to customize some of them, but still not much improvement. 我尝试了许多算法(在其他SO帖子中提到),甚至尝试自定义其中一些算法,但仍然没有太多改进。
I would really appreciate any kind of help in this. 我真的很感谢任何帮助。 Thanks in advance for your help. 在此先感谢您的帮助。
You could take a recursive function which separates all key/value pairs and build a new cartesian product by iterating the values, if an array with objects call getCartesian
again and build new objects. 如果具有对象的数组再次调用getCartesian
并构建新的对象,则可以采用递归函数,该函数将所有键/值对分开并通过迭代值来构建新的笛卡尔积。
The referenced link does not work, because of the given arrays of objects which the linked answer does not respect. 所引用的链接不起作用,因为链接的答案不遵守给定的对象数组。
function getCartesian(object) { return Object.entries(object).reduce((r, [k, v]) => { var temp = []; r.forEach(s => (Array.isArray(v) ? v : [v]).forEach(w => (w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x => temp.push(Object.assign({}, s, { [k]: x })) ) ) ); return temp; }, [{}]); } var data = { name: "name here", skills: ["cash", "shares"], subjects: [{ subName: "subject1", remark: ['remark1', 'remark2'] }, { subName: "subject2", remark: ['remark1', 'Hockey'] }] }; console.log(getCartesian(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.