Store data in Local Storage from JSON file

Discussion in 'JavaScript' started by ManpreetWeb, Sep 14, 2020.

  1. #1
    I am trying to store data in the local Storage from my JSON file. But I am getting an empty array in the local Storage. File name is 'data' in the project.
    [
    "friends": [
    {
    "id": 0,
    "name": "Daugherty Gould"
    },
    {
    "id": 1,
    "name": "Foley Carpenter"
    },
    {
    "id": 2,
    "name": "Brewer Vinson"
    }
    ]

    localStorage.setItem('firstName',data.friends.name );

    I am not getting the right output with above code. How can I get all the names in localstorage.

    Thank you in advance!
     
    ManpreetWeb, Sep 14, 2020 IP
  2. hdewantara

    hdewantara Well-Known Member

    Messages:
    538
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #2
    Hi.
    if the data object is formatted as:
    
    data={"friends":[{"id":0,"name":"daugherty gold"},{"id":1,"name":"foley carpenter"}]};
    Code (JavaScript):
    then through Firefox Console, I could set firstName to be "daugherty gold" with following statement:
    
    localStorage.setItem('firstName',data.friends[0].name);
    Code (JavaScript):
    And to get the value, I could use:
    
    localStorage.getItem('firstName');
    Code (JavaScript):
     
    hdewantara, Sep 14, 2020 IP