[Vuejs]-JavaScript add json to existing object

2👍

From what I see, the missing values to create the final output are the key properties of the options arrays, which I see in the first attributes array under the text property of the title object.

The first change that you can do is on the creation of the parts variable: instead of returning the attribute.values directly, map over them to save the attribute.title.text as well.

At the same time, we set the keys of the returned object to match the options object from the desired output.

const parts = this.form.attributes.map((attribute) =>
  attribute.values.map((value) => {
    // `options` objects have `value` and `key` properties
    return { value, key: attribute.title.text };
  })
);

The combinations code remains the same.

Then, we loop over the combinations and create the new variants array

let variants = [];

for (const combination of combinations) {
  variants.push({
    // use template strings to create the new title
    title: `${combination[0].value}/${combination[1].value}`,
    slug: "...the value that you want",
    // the "combination" variable already has the structure that you want for "options"
    options: combination
  });
}

The final code will look something like this:

addVariant: function () {
  const parts = this.form.attributes.map((attribute) =>
    attribute.values.map((value) => {
      return { value, key: attribute.title.text };
    })
  );

  const combinations = parts.reduce((a, b) =>
    a.reduce((r, v) => r.concat(b.map((w) => [].concat(v, w))), [])
  );

  let variants = [];

  for (const combination of combinations) {
    variants.push({
      title: `${combination[0].value}/${combination[1].value}`,
      slug: "...the value that you want",
      options: combination,
    });
  }

  this.variants = variants;
}

Leave a comment