Retrieving the values from unspecified keys within an array of objects

Receiving a JSON from an external source with an unpredictable number of keys is the challenge. The structure typically appears as follows:

data = [{
id: 1,
testObject_1_color: "red",
testObject_1_shape: "triangle",
testObject_2_color: "blue",
testObject_2_shape: "line",
},{
id: 2,
testObject_1_color: "green"
testObject_1_shape: "triangle",
},{
id: 3,
testObject_1_color: "brown",
testObject_1_shape: "square",
testObject_2_color: "black",
testObject_2_shape: "circle",
testObject_3_color: "orange"
testObject_3_shape: "square",
}]

To effectively process this data, transforming it into a more manageable format would be ideal:

data = [
{object:1, color:"red", shape:"triangle"},
{object:2, color:"blue", shape:"line"},
{object:3, color:"green", shape:"triangle"}
]

The fluctuating number of testObject_x_color / shape properties makes iterating through the collection daunting without resorting to repetitive checks like

if data.hasOwnProperty('testObject_x_color')...
. Any suggestions on how to navigate this gracefully?

Answer №1

Below is another approach utilizing several loops:

var items = [{
  id: 1,
  testObject_1_color: "red",
  testObject_1_shape: "triangle",
  testObject_2_color: "blue",
  testObject_2_shape: "line"
}, {
  id: 2,
  testObject_1_color: "green",
  testObject_1_shape: "triangle"
}, {
  id: 3,
  testObject_1_color: "brown",
  testObject_1_shape: "square",
  testObject_2_color: "black",
  testObject_2_shape: "circle",
  testObject_3_color: "orange",
  testObject_3_shape: "square"
}];

var organizedData = items.reduce(function(accumulator, current) {
  
  var tempObj = {};
  
  Object.keys(current).forEach(function(key) {
    
    var parts = key.split('_');
    
    if (parts.length === 3) {
      if (!tempObj[parts[1]]) {
        tempObj[parts[1]] = {};
      }
      tempObj[parts[1]][parts[2]] = current[key];
    }
  });
  
  Object.values(tempObj).forEach(function(pair) {
    accumulator.push(pair);
  });
  
  return accumulator;
}, []);

for (var index = 0; index < organizedData.length; index++) {
  console.log('object ' + (index + 1) + ': ', organizedData[index]);
}

Answer №2

implement the use of regular expressions and ES5 array functions.

let data = [{
    id: 1,
    testObject_1_color: 'red',
    testObject_1_shape: 'triangle',
    testObject_2_color: 'blue',
    testObject_2_shape: 'line'
  },
  {
    id: 2,
    testObject_1_color: 'green',
    testObject_1_shape: 'triangle'
  },
  {
    id: 3,
    testObject_1_color: 'brown',
    testObject_1_shape: 'square',
    testObject_2_color: 'black',
    testObject_2_shape: 'circle',
    testObject_3_color: 'orange',
    testObject_3_shape: 'square'
  }
]
let regId = /testObject_(\d{1,3})_(color|shape)/
let res = data
  .reduce((re, obj) => {
    Reflect.ownKeys(obj)
      .filter(key => key !== 'id')
      .forEach(key => {
        let id = obj.id + '' + key.match(regId)[1]
        let isFind = re.find(o => o.id === id)
        if (!isFind) {
          re.push({
            id: obj.id + '' + key.match(regId)[1],
            color: obj[key]
          })
        } else {
          isFind.shape = obj[key]
        }
      })
    return re
  }, [])
  .map(({ id, color, shape }, index) => ({
    id: index + 1,
    color,
    shape
  }))
console.log(res)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

Generate responsive elements using Bootstrap dynamically

I'm having success dynamically generating bootstrap elements in my project, except for creating a drop-down menu. ColdFusion is the language I am using to implement these div elements: <div class="panel panel-primary"><div class="panel-head ...

Various criteria and unspecified length for input needed

I am currently working on implementing a struct called "objective" in my program. This struct has the following components: a character array named "name" with a maximum capacity of 8000 characters (although it will usually be much smaller), an integer "id ...

Guidelines for integrating historyAPI with AngularJS

I am currently working on developing a prototype similar to qz.com. Here is the strategy I am following: Create a function that loads the next piece of content when scrolling to the bottom of the page. This function will also update the URL using either ...

Border becomes dashed when dragging and dropping

I am working on enabling drag and drop functionality for users. When an item is lifted from its original position, a gray dashed box should appear in its place. As the item is moved closer to another spot, the containers adjust to create a target area (gra ...

Mongoose is having trouble identifying the 2dsphere index I created

I am currently attempting to add a 2dSphere index for the field startLocation within the tourSchema. This is how it is defined: startLocation: { type: { type: String, default: 'Point', enum: ['Point'] ...

Obtain the indices of a 2D array jQuery element within a callback function

I am working with a 2D array of JQuery elements, also known as a Grid. My goal is to access the specific index i and j of the element Grid[i][j] from within the callback function of an addEventListener(). Does anyone know how I can achieve this? grid[i][ ...

PHP: Retrieve different options from an array

Can I achieve the desired outcome using the following array? array ( [0] => array ( [0] => 'Size', [variation_id] => array ( [0] => 'S', [1] => 'M& ...

Keep subtracting pairs of numbers within an array until there is only one integer left in the array

Given an integer array: int[] array= {5, 7, 16, 3, 2} I am looking to create a program that calculates the difference between elements in the array up to each single element. Array → {5, 7, 16, 3, 2} [1] Difference → {2, 9, -13, -1} [2] Difference ...

Transforming a React Class Component into a React Functional Component

After struggling for a day with multiple failed attempts, I have been unsuccessful in converting a React Class Component. The original class component code is as follows: class NeonCursor extends React.Component { constructor(props) { super(props); ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Can you retrieve data or HTML content from the main Vue 3 component?

I have experience using Vue in previous projects but I'm currently facing some challenges on how to pass information/arguments to a root Vue 3 component. My goal is to set up something like this in my HTML: <div class="nav-app" nav=&quo ...

What is the best way to access the Nodejs response object from outside the routing function?

Having an issue with obtaining a response object from outside the router function in Nodejs back-end. I can successfully log the response object in the first routing function, however, I am unable to access the values in the console of the second routing f ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

I am attempting to trigger a mouseup event following a mousedown action

elements[0].onmousedown = function(){ console.log('screen clicked.'); triggerMouseUp(); }; I just need to incorporate a function in my code that simulates mouseup event, even when the user is still holding down the click button. e ...

What sets the Object Class definition apart in importance?

How can we ensure that three instances of Item are unique variables with their own self-contained data, rather than just being duplicates with different names? class Item(object): def __init__(self): self.ID=None self.name=None item ...

Challenges arise when the value of an element within an entity is 'undefined'

I'm having difficulty sorting and grouping an array of objects. The problem arises when attempting to access the key named 'Driver' as it is returning 'undefined'. Here is the snippet of code in question: let driversList = [ ...

Tips for enabling the OnLoad Event for a React Widget

Hey there! I'm a beginner with React and I'm struggling to call a function once after the component is created. I tried adding an onLoad event in the component creation, but it's not working as expected. The function 'handleClick' ...

Creating a personalized progress bar that reflects real-time data from an external API

I have developed an API that sends scores if someone solves math, chemistry, or physics problems correctly. The API responds with a JSON object like this: { "scores": { "maths": 28, "chemistry": 9, "physics": 26, } } When a person complet ...

Drop the <span> element into a paragraph by utilizing JQuery's drag and drop feature

Trying to drag and drop <span> into <p>. The code is functional, but encountering 3 issues: When editing content inside <p> by typing (e.g. three words) and then dragging <span> into <p>, the newly typed words are consider ...