-2

I'm writing a small js snippet that should return values based on the keys from object. The object can be nested even, here is my code.

let obj = {
  "name": "Family",
  "count": 6,
  "children": {
    "name": "Jim",
    "age": "24",
    "address": {
      "street": "5th ave",
      "state": "NY",
      "country":"US"
    }
  },
  "parents": {
    "name": "John",
    "age": "45",
    "address": {
      "street": "New brew st",
      "state": "CA",
      "country":null
    }
  }
};

const getData = (obj) => {
  let jsonString = obj;
  let keys = ["name", "count","children.address.street"];
  let returnString = "";
  keys.forEach((item) => {
    returnString += buildString(item, jsonString) + "$$";
  })
  return returnString.replace(/(\$\$)*$/, "");
}

const buildString = (keyIn, data) => {
  var value = '';
  if (keyIn.includes('.'))
    value = splitAndReturn(keyIn, data);
  else
    value = data[keyIn] ? data[keyIn] : null;
  return `${keyIn}###${value}`;
};

const splitAndReturn = (keyIn, obj) => {
  let nKeyArr = keyIn.split('.');
  let buildString = 'obj';
  nKeyArr.forEach(item => {
    buildString += `['${item}']`
  });
  let nKey = buildString;
  return (nKey)
}

console.log(getData(obj));

I'm thinking in this way, whenever there is a . in my keys, I want to call a new function that will be converted into [''] format and at the end return obj[''].

for eg. If I pass in children.name I should get Jim, and If I pass in children.address.country I should get US.

But currently, I'm returning a string, I am not sure how can I get the result of the key. Can someone please let me know how can I achieve this?

user3872094
  • 3,269
  • 8
  • 33
  • 71
  • 1
    Does this answer your question? [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path) – 0stone0 Apr 29 '22 at 15:33

1 Answers1

2

A small recursive function could allow you to access nested keys to your object.

function getValue(initialKey, obj) {
  const [key, ...rest] = initialKey.split(".");

  if (obj[key] == null) {
    return null;
  }
  
  if (rest.length) {
    return getValue(rest.join("."), obj[key]);
  }
  
  return obj[key];
}

const data = {
  name: 'Family',
  count: 6,
  children: {
    name: 'Jim',
    age: '24',
    address: {
      street: '5th ave',
      state: 'NY',
      country: 'US',
    },
  },
  parents: {
    name: 'John',
    age: '45',
    address: {
      street: 'New brew st',
      state: 'CA',
      country: null,
    },
  },
};
console.log(getValue("children.name", data));
console.log(getValue("children.address.country", data));
Jonathan Hamel
  • 1,393
  • 13
  • 18