How to get the combination of array values from nested arrays in an array of objects

Issaki

I have an array of objects with the following structure:

 var varientSections = [
  {
    type: "frame",
    values: ["black", "white", "wood"]
  },
  {
    type: "finish",
    values: ["matte", "glossy"]
  }
];

I want to get the combination of the array values and create a new list with it. Right now, I am able to retrieve the combination from the nested array values using the method called getCombination(varientSections). However, I do not know how to create a new list with the following structure:

var results = [
  {
    attributes: [
      {
        type: "frame",
        value: "black"
      },
      {
        type: "finish",
        value: "matte"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "black"
      },
      {
        type: "finish",
        value: "glossy"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "white"
      },
      {
        type: "finish",
        value: "matte"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "white"
      },
      {
        type: "finish",
        value: "glossy"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "wood"
      },
      {
        type: "finish",
        value: "matte"
      }
    ]
  },
  {
    attributes: [
      {
        type: "frame",
        value: "wood"
      },
      {
        type: "finish",
        value: "glossy"
      }
    ]
  }
];

Below is my code:

function getCombinations(arr) {
  if (arr.length === 0) {
    return [[]];
  }

  let [current, ...rest] = arr;
  let combinations = getCombinations(rest);

  var result = current.values.reduce(
    (accumulator, currentValue) => [
      ...accumulator,
      ...combinations.map(c => [currentValue, ...c])
    ],
    []
  );
  console.log("result is ");
  console.log(result);
  return result;
}

let varientCombinations = getCombinations(varientSections);
console.log(varientCombinations);

let updatedVarientDetails = [];
varientSections.forEach((varientSection, index) => {
  let type = varientSection.type;
  varientCombinations.forEach(combination => {
    let obj = [
      {
        type: type,
        value: combination[index]
      },
    ];
    updatedVarientDetails.push(obj);
  });
});

console.log(updatedVarientDetails);
Nina Scholz

You could get the cartesian product and give it later the wanted style. The names and values are taken form the handed over object.

The algorithm takes all key/value pairs and has a stric view to the values, that means if an array is found or an object, hence w && typeof w === "object", the actual part is taken an used for adding additional key/value pairs.

For example a small object with two properties

{ a: 1, b: [2, 3] }

yields

[
    { a: 1, b: 2 },
    { a: 1, b: 3 }
]

A bit more advanced object, like

{ a: 1, b: { c: { d: [2, 3], e: [4, 5] } } }

yields the same structure as given

[
    {
        a: 1,
        b: {
            c: { d: 2, e: 4 }
        }
    },
    {
        a: 1,
        b: {
            c: { d: 2, e: 5 }
        }
    },
    {
        a: 1,
        b: {
            c: { d: 3, e: 4 }
        }
    },
    {
        a: 1,
        b: {
            c: { d: 3, e: 5 }
        }
    }
]

Thant means, from any found sub object the cartesian product is taken and combined with the actual values.

const
    getCartesian = object => Object.entries(object).reduce(
        (r, [key, value]) => {
            let temp = [];
            r.forEach(s =>
                (Array.isArray(value) ? value : [value]).forEach(w =>
                    (w && typeof w === "object" ? getCartesian(w) : [w]).forEach(x =>
                        temp.push({ ...s, [key]: x })
                    )
                )
            );
            return temp;
        },
        [{}]
    ),
    data = [{ type: "frame", value: ["black", "white", "wood"] }, { type: "finish", value: ["matte", "glossy"] }],
    result = getCartesian(data)
        .map(o => ({ attributes: Object.assign([], o).map(({ ...o }) => o) }));

console.log(result);

console.log(getCartesian({ a: 1, b: { c: { d: [2, 3], e: [4, 5] } } }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to use reduce to retrieve values from deep nested array objects

分類Dev

How to get all values of objects inside array

分類Dev

How to put values of objects from an array into a string

分類Dev

How to get unique an array of objects back from a complex an array of objects?

分類Dev

How to get an Array of Objects from Firestore in Swift?

分類Dev

How to get a the sum of multiple arrays within an array of objects?

分類Dev

How to get all keys with values from nested objects

分類Dev

How to get common values from 4 multidimensional arrays using array_intersect

分類Dev

How to get a particular attribute from an array of array objects?

分類Dev

How can I convert an array of arrays to an array of objects, selecting the key from other array?

分類Dev

Get count from Array of arrays

分類Dev

PHP - How to remove duplicate values from array (compare 2 arrays)

分類Dev

How to get a nested array into rowData

分類Dev

Nested ng-repeat with array of objects which contain arrays

分類Dev

how to get a particular object value from nested json array

分類Dev

jQuery - How to get JSON array name from nested JSON

分類Dev

Convert array of objects to array of arrays

分類Dev

How to make an array of multiple nested objects?

分類Dev

get a set of values from an array

分類Dev

How to get the sum of number from an array of objects, using pure JS?

分類Dev

Get all the nested arrays from main array and merge each of them according to keys Knockout.Js

分類Dev

Create nested associative array from foreach values

分類Dev

Search nested array of objects

分類Dev

how to query nested array of objects by also filtering nested array of nested array in mongo

分類Dev

How to count items in arrays of values in an array of hashes

分類Dev

filter array of objects with underscore and get new array of values

分類Dev

How to get values in array of array in angular?

分類Dev

Get values from array and using the values in a program

分類Dev

How to get text values to an array?

Related 関連記事

  1. 1

    How to use reduce to retrieve values from deep nested array objects

  2. 2

    How to get all values of objects inside array

  3. 3

    How to put values of objects from an array into a string

  4. 4

    How to get unique an array of objects back from a complex an array of objects?

  5. 5

    How to get an Array of Objects from Firestore in Swift?

  6. 6

    How to get a the sum of multiple arrays within an array of objects?

  7. 7

    How to get all keys with values from nested objects

  8. 8

    How to get common values from 4 multidimensional arrays using array_intersect

  9. 9

    How to get a particular attribute from an array of array objects?

  10. 10

    How can I convert an array of arrays to an array of objects, selecting the key from other array?

  11. 11

    Get count from Array of arrays

  12. 12

    PHP - How to remove duplicate values from array (compare 2 arrays)

  13. 13

    How to get a nested array into rowData

  14. 14

    Nested ng-repeat with array of objects which contain arrays

  15. 15

    how to get a particular object value from nested json array

  16. 16

    jQuery - How to get JSON array name from nested JSON

  17. 17

    Convert array of objects to array of arrays

  18. 18

    How to make an array of multiple nested objects?

  19. 19

    get a set of values from an array

  20. 20

    How to get the sum of number from an array of objects, using pure JS?

  21. 21

    Get all the nested arrays from main array and merge each of them according to keys Knockout.Js

  22. 22

    Create nested associative array from foreach values

  23. 23

    Search nested array of objects

  24. 24

    how to query nested array of objects by also filtering nested array of nested array in mongo

  25. 25

    How to count items in arrays of values in an array of hashes

  26. 26

    filter array of objects with underscore and get new array of values

  27. 27

    How to get values in array of array in angular?

  28. 28

    Get values from array and using the values in a program

  29. 29

    How to get text values to an array?

ホットタグ

アーカイブ