Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

how can i change the first object value as second object key names in javascript

0 Kudos

input

Array1=[ { "col1":"studentname", "col2":"rolno", "col3":"gp_name" }, { "col1":"mohan", "col2":"123", "col3":"maths" }, { "col1":"mahesh", "col2":"1234", "col3":"computer" } ];

expected output


[{ "studentname":"mohan", "rolno":"123", "gp_name":"maths" }, { "studentname":"mahesh", "rolno":"1234", "gp_name":"computer" }]

3 REPLIES 3

pfefferf
Active Contributor
0 Kudos

One simple option:

const source = [
    { "col1": "studentname", "col2": "rolno", "col3": "gp_name" },
    { "col1": "mohan", "col2": "123", "col3": "maths" },
    { "col1": "mahesh", "col2": "1234", "col3": "computer" }
  ];

const header = source.shift();

const headerMap = new Map();
for(var prop in header) {
  headerMap.set(prop, header[prop]);
}

const target = source.map((entry) => {
    let res = {};
    for (var [key, value] of headerMap.entries()) {
      res[value] = entry[key];
    }
    return res;
});

0 Kudos

thanks

can u help me for dynamic column name also . in real col1,col2....value can be more than 10 sometime 12 how to add the column name dynamically based on the length .

i cannot hardcode the column name directly . .every column name starts with col only . based on the count length it will increase the col1,or col2,col3

pfefferf
Active Contributor
0 Kudos

Updated the answer to fulfill the "dynamic" part.