Array Structure Conversion

Hey Folks!

I have some dynamically generated data I need to convert:

[
  {
    "array": 475,
    "name": "Grey",
    "attribute_id": 103
  },
  {
    "array": 504,
    "name": "Ridgeback",
    "attribute_id": 104
  },
  {
    "array": 510,
    "name": "Large",
    "attribute_id": 105
  },
  {
    "array": 511,
    "name": "Medium",
    "attribute_id": 105
  },
  {
    "array": 508,
    "name": "X-Large",
    "attribute_id": 105
  }
]

For example, but i need them it to end up like the below:

[
  {
    "attribute": 103,
    "valueIds": [
      475
    ]
  },
  {
    "attribute": 104,
    "valueIds": [
      504
    ]
  },
  {
    "attribute": 105,
    "valueIds": [
      510,
      511,
      508
    ]
  }
]

So, in a function node, I have the idea to flatten into two arrays, and iterate through them, with a floating offset, like so, but it’s not quite returning what I need:

//convert values to arrays

var attributeValues = [];
var attributeParentIds = [];
var i = 0;
var L = items.length;

while (i < L) {
attributeValues.push(items[i].json.array);
attributeParentIds.push(items[i].json.attribute_id);
i++;
};

//iterate through attributeParentIds, per seperate attribute

i = 0;
var attributesJson = []

while (i < L) {
  var array = [];
  var currentAttribute = attributeParentIds[i];
  var matchingLength = 0;
  
//determine amount of array that matches currentAttribute

  while (attributeParentIds[i+matchingLength] == attributeParentIds[i+matchingLength+1]) {
    matchingLength++;
  };

//push the counted number of attributeValueIds to the array

  for (let i2 = 0; i2 < matchingLength; i2++) {
    array.push (attributeValues[i2+i]);
  }

//push to the json

attributesJson.push({attribute: currentAttribute, valueIds: array});
i = i + matchingLength + 1;
  
}

return {
    attributesJson
  }

Can anyone offer any insight?

Needed a <= !

Cheers for looking

2 Likes