skip to Main Content

is it possible to use dynamic props to get the nested value of javascript object as below, because I am getting error with this. please suggest me any solution.

Component.

import Link from "next/link";
import { info } from "@/lib/info";

export default function Tip({ name }) {
  return (
      <div>
        <div>
          <header>
            <p className="text-sky-400"> {info.${name}.title}</p>
          </header>
          <div>
            <div className="max-w-80">
              <p className="text-justify">{info.${name}.content}</p>
              <Link
                className="flex text-sky-700 pl-2 font-bold justify-end"
                target="blank"
                href={info.${name}.href}
              >
                Read more ...
              </Link>
            </div>
          </div>
        </div >
  );
}

Using the component.

<Tip name="accruedinterest" />

Array

export const info = {
  acrruedinterest: {
    title: "accrued interest",
    content:
      "In finance, accrued interest is the interest on a bond or loan that has accumulated since the principal investment, or since the previous coupon payment if there has been one already.",
    href: "https://en.wikipedia.org/wiki/Accrued_interest",
  },
  acrruedcosine: {
    title: "inverse cosine",
    content:
      "The inverse trigonometric functions are the inverses of the sine, cosine, tangent, cotangent, secant, and cosecant functions, and are used to obtain an angle from any of the angle's trigonometric ratios.",
    href: "https://en.wikipedia.org/wiki/Inverse_trigonometric_functions",
  },
  inversehyperbolic: {
    title: "inverse hyperbolic",
    content:
      "In mathematics, the inverse hyperbolic functions are invers of the hyperbolic functions, analogous to the inverse circular functions. There are six in common use: inverse hyperbolic sine, inverse hyperbolic cosine, inverse hyperbolic tangent, inverse hyperbolic cosecant, inverse hyperbolic secant, and inverse hyperbolic cotangent.",
    href: "https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions",
  },
} 

2

Answers


  1. You can’t use dot notation with template strings to access properties in a JavaScript object. Instead, you should use bracket notation like info[name] to dynamically retrieve nested values.

    Here’s an updated version of your code:

    <p className="text-sky-400">{info[name]?.title}</p>

    Be sure to also pass the right key as a prop in the Tip Component. I believe you meant to type acrruedinterest instead

    Login or Signup to reply.
  2. Agree with the answer from @Ayantunji.

    Still adding some more context by this post.

    As we know, a JavaScript object is an associated array as well.

    It may mean the following:

    const plainObject = {
      firstItem: 'Good Morning',
      secondItem: 'to All',
      thirdItem: 'of you',
    };
    

    The above JavaScript object is also equivalent to the following associated array.

    const associativeArray = [];
    associativeArray['firstItem'] = 'Good Morning';
    associativeArray['secondItem'] = 'to All';
    associativeArray['thirdItem'] = 'of you';
    

    However, the above array is not an ordinary JavaScript array, but it is an associated array. An ordinary array will only have numeric indexes. However, an associated array will only have string indexes as in this case.

    Since a JavaScript object is an associated array as well, the following all references are valid.

    console.log(plainObject['firstItem']);  // Good Morning
    console.log(plainObject.firstItem);  // Good Morning
    console.log(associativeArray['firstItem']);  // Good Morning
    console.log(associativeArray.firstItem);  // Good Morning
    

    And now answering to the question :

    While accessing an object, its property must be hard coded in the source code as we have done above. However while accessing an object as an associated array, we have options :- it can be still hard coded as well as referenced by variables.

    The following code shows the JavaScript object accessed as an associated array by referencing a variable.

    const propsName = 'firstItem';
    console.log(plainObject[propsName]);  // Good Morning
    console.log(associativeArray[propsName]);  // Good Morning
    

    Please also note that variable reference is not possible while accessing an object. The following two statements will result the value undefined.

    console.log(plainObject.propsName);  // undefined
    console.log(associativeArray.propsName);  // undefined
    

    A special note:

    The way you have tried the same is shown below. At present it does not meet the syntax of a template literal, therefore it is resulting an syntax error.

    const href = info.${name}.href;
    

    The syntax error may be rectified as below. However in that case, it will just result the string ‘info.accruedinterest.href’. It will still not access the object and get its value.

    const name = 'accruedinterest';
    const href = `info.${name}.href`; // info.accruedinterest.href
    

    By accessing this way will give you the result:

    const name = 'accruedinterest';
    const href = info[name].title // "https://en.wikipedia.org/wiki/Accrued_interest"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search