skip to Main Content

Suppose I want to replace all Json items before colons with my array respectively using JavaScript, how do I go about it.
As you may see below, is a Json object representing column names and first row. I want to replace column names position-wise with values from an array shown below.

// Json object
const Json = "{id: '1', name: 'Abednego Nasila', Reg: '123'}"

And below is my array

//array variable
const arr = ['myId', 'Student_name', 'Adm.no']

My desired output should be as shown below:

"{myId: '1', Student_name: 'Abednego Nasila', Adm.no = '123'}"

Thanks

Any help help will be appreciated.

2

Answers


  1. The problem is that your source JSON is, in fact, not a valid JSON string.
    Therefore, to convert it into an object, I’m using a bit hackish solution. I wouldn’t recommend using this approach in a real production environment. You probably want to convert your source string into a valid JSON first instead.

    Anyway, here is how this can be achieved:

    // Json object
    const Json = "{id: '1', name: 'Abednego Nasila', Reg: '123'}"
    
    //array variable
    const arr = ['myId', 'Student_name', 'Adm.no']
    
    let source = {};
    eval('source = ' + Json);
    
    const result = {};
    arr.forEach((field, index) => result[field] = Object.values(source)[index]);
    
    console.log(result);
    Login or Signup to reply.
  2. Here is a function that replaces the keys in a given JSON String with keys from a given Array.

    Now go study:

    // create a real json string from an object
    let REALJSON = JSON.stringify( {id: 1, name: 'Abednego Nasila', Reg: 123} );
    
    console.log(`the JSON: ${REALJSON}`);
    
    //array variable
    const JSONReplaceKeys = (JSONStr, nwKeys) => {
      // parse the JSON
      const obj = JSON.parse(JSONStr);
      // create an Array with keys/values from obj
      const nwObj = Object.entries(obj)
      // use a reducer to create a new Object with the new keys
      .reduce( (acc, [key, value], i) => 
        ({...acc, [nwKeys[i]]: value }), {});
      // stringify the new Object
      return JSON.stringify(nwObj);
    }
    
    // let's try it
    REALJSON = JSONReplaceKeys(REALJSON, ['myId', 'Student_name', 'Adm_no']);
    
    console.log(`the new JSON ${REALJSON}`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search