0

I have an object called data like this:

var data = {
  operators: {
    operator1: {
      top: 20,
      left: 20,
      properties: {
        title: 'Operator 1',
        inputs: {},
        outputs: {
          output_1: {
            label: 'Output 1',
          },
          output_2: {
            label: 'Output 2',
          }
        }
      }
    },
    operator2: {
      top: 80,
      left: 300,
      properties: {
        title: 'Operator 2',
        inputs: {
          input_1: {
            label: 'Input 1',
          },
          input_2: {
            label: 'Input 2',
          },
          input_3: {
            label: 'Input 3',
          },
        },
        outputs: {}
      }
    },
  },
};

How to get a value from data by a key.

function myFunction(data, key) {
  //Find in data with key, and return value.
}

Result: var result = myFunction(data,'output_1') = Output 1 (get by Title).

lumio
  • 7,428
  • 4
  • 40
  • 56
P. Pogba
  • 175
  • 1
  • 2
  • 13

2 Answers2

1

A simple solution could be:

function myFunction(data,key){
  if(data[key]){
    return data[key];
  }else{
    return myFunction(data[key],key);
  }
}
Shubham
  • 1,755
  • 3
  • 17
  • 33
Jayyrus
  • 12,961
  • 41
  • 132
  • 214
1

You could use an iterative and recursive approach and exit early if found.

The function getValue returns an object if found, otherwise it returnes false.

To get the value, you could take the property value.

function getValue(object, key) {
    var result;
    return Object.keys(object).some(function (k) {
        if (k === key) {
            result = { value: object[k] };
            return true;
        }
        if (object[k] && typeof object[k] === 'object' && (result = getValue(object[k], key))) {
            return true;
        }
    }) && result;    
}

var data = { operators: { operator1: { top: 20, left: 20, properties: { title: 'Operator 1', inputs: {}, outputs: { output_1: { label: 'Output 1' }, output_2: { label: 'Output 2' } } } }, operator2: { top: 80, left: 300, properties: { title: 'Operator 2', inputs: { input_1: { label: 'Input 1' }, input_2: { label: 'Input 2' }, input_3: { label: 'Input 3', foo: null } }, outputs: {} } } } };

console.log(getValue(data, 'output_1').value); // { label: 'Output 1' }
console.log(getValue(data, 'foo').value);      // null
console.log(getValue(data, 'bar'));            // false
console.log(getValue(data, 'bar').value);      // undefined
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392