skip to Main Content

I’m trying to create an object with dynamic keys with key ID and value as a name from a string that I’m getting through API.
Below is my API

["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]

I want to convert it to following response

         [
            { id: 0, name: "PHP" },
            { id: 1, name: "Project Management" },
            { id: 2, name: "PHP dynamic website" },
            { id: 3, name: "Ecommerce" }
         ]

5

Answers


  1. Just use a forEach loop, and use the iterator as the key:

    var apiResponse = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"],
        newResponse = [ ];
    
    apiResponse.forEach(function(name, index) {
       newResponse.push({ id: index, name: name });
    });
     
     console.log(newResponse);
    Login or Signup to reply.
  2. There no dynamic keys in here tho, all your objects and their keys look the same… Simply use the array.forEach() method to loop on all array values and push them into object into a new array:

    let res = [];
    sourceArr.forEach( (name, index) => {
       res.push( {id: index, name: name} );
    }
    

    Easy as that.

    Login or Signup to reply.
  3. You can map each name to an object which uses the index as the id and the value as the name property:

    const arr = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"];
    
    const res = arr.map((name, id) => ({id, name}));
    console.log(res);
    Login or Signup to reply.
  4. Considering your usecase: Assuming newArr is the type of array you want
    // ar is the initial array

    ar=["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"];
    newArr=[];
    for(i=0;i<ar.length;i++){
      let obj={id:i,name:ar[i]};
      newArr.push(obj);
    }
    console.log(newArr);
    Login or Signup to reply.
  5. I used traditional way. hope you are looking for this one.

    B = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]
    result = [];
    
    for (i=0;i<B.length;i++)
    {
        result[i] = "{id:"+[i]+ "name:"+B[i]+"}";
    }
    console.log(result);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search