Cartesian product of javascript object with different types of values like string, object and array

前端 未结 1 1185
野的像风
野的像风 2021-01-24 06:34

I am working on an assignment. I have the following object form.

{
    name: \"name here\",
    skills:  [ \"cash\", \"shares\" ],
    subjects: 
    [ 
      {
         


        
相关标签:
1条回答
  • 2021-01-24 07:14

    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.

    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; }

    0 讨论(0)
提交回复
热议问题