Home > front end >  build string keys and get a value
build string keys and get a value

Time:04-30

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?

CodePudding user response:

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));

  • Related