Home > Back-end >  Render nested string inside of object
Render nested string inside of object

Time:11-29

I'm trying to render a dynamic list of fields from a JSON file. Some fields have to go through this accountFieldMap object I created for key renaming purposes.

For example it finds the key userFirstName1 from the JSON and renders the value of it as firstName at the component.

  const accountFieldMap = {
    firstName: "userFirstName1",
    lastName: "userLastName1",
    ID: "userID",
    location: `userLocation.city`,
  };

The only issue is with the location field. How can I let JavaScript know that it should render that city nested field and show it as location?

CodePudding user response:

If I understand you correctly, location.city is a path to some value in object.

There are some libraries for this like lodash, which have inbuilt functions that can resolve that, but if you want to do it in vanilla js, you can do it by splitting this string by dot and going through that array to get a value.

const getByPath = (path, obj) => {
  const splittedPath = path.split(".");
  return splittedPath.reduce((acc, curr) => {
      acc = obj[curr];
      return acc;
  }, obj)
}

So in this case if you have object like

const testObj = {
  location: {city: "Kyiv"},
  firstName: "Oleg"
}

It will return you "Kyiv" if you will pass into getByPath "location.city" as path. And it will also work in case if there is no nesting, so

getByPath("firstName", testObj)

will return you "Oleg"

CodePudding user response:

you only have to map the array and create a new object;

import fileData from "../path/to/json";

const people = fileData.arrayName.map(person => ({
    firstName: person.userFirstName1,
    lastName: person.userLastName1,
    ID: person.userID,
    location: person.userLocation.city,
}));
  • Related