2

У меня есть массив

['one','two','three']

И объект

{
    'one':{
        'two':{
            'three': 'data'
        }
    }
}

как мне получить 'data'?

3 ответа 3

7

Один из способов - использовать функцию reduce.

const props = ['one', 'two', 'three']

const data = {
  'one': {
    'two': {
      'three': 'data'
    }
  }
}

const val = props.reduce((elem, prop) => {
  return elem[prop];
}, data);

console.log(val);

Второй способ, с помощью обычного цикла.

const props = ['one', 'two', 'three']

const data = {
  'one': {
    'two': {
      'three': 'data'
    }
  }
}
let val = data;
for (let i = 0; i < props.length; i++) {
  val = val[props[i]];
}

console.log(val);

Путь маньяка. НЕ ДЕЛАЙТЕ ТАК!

const props = ['one', 'two', 'three']

const data = {
  'one': {
    'two': {
      'three': 'data'
    }
  }
}
const func = new Function('data', 'return data.' + props.join('.'));

const val = func(data);

console.log(val);

1

var test_data = {
  'one': {
    'two': {
      'three': 'data'
    }
  }
};
var test_keys = ['one', 'two', 'three'];

function getSubitem(data, keys) {
  var current = data;
  for (var i = 0; i < keys.length; i++) {
    current = current[keys[i]];
    if (!current)
      return null;
  }
  return current;
}

console.log(getSubitem(test_data, test_keys));

1
  • Можно давать путь через точки 'document.body.xyz' или через массив ['document', 'body', 'xyz'].
  • Можно указать значение по умолчанию
  • Для пути в виде строки можно задать произвольный разделитель(последний аргумент)

function resolvePath (path, obj , orDefault = null, separator = '.') {
    const properties = Array.isArray(path) ? path : path.split(separator)
    return properties.reduce((prev, curr) => prev && prev[curr], obj) || orDefault
}

// Примеры использования
console.log(
resolvePath('document.body', window), // <body>
resolvePath('document.body.xyz', window), // null
resolvePath(['document', 'body', 'xyz'], window, 'defaultValue') // defaultValue
)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.