简体   繁体   中英

Replace keys based on another array of objects

I have two array of objects, Based on one array I need to replace the key of another array. Tried to use Object.Keys() but could not achieve it. Kindly suggest

 // **Input:** let sim = { "header": [{ "VKORG": "1000", "VTWEG": "10" }, { "VKORG": "1000", "VTWEG": "20" } ] } // **Reference Array:** let columns = [{ "FIELD": "VKORG", "FIELD_DESC": "Sales Organization" }, { "FIELD": "VTWEG", "FIELD_DESC": "Distribution Channel" } ] /// **Code I tried** for (let i = 0; i < sim.header.length; i++) { if (Object.keys(sim[i].header) === Object.keys(columns[i].header)) { sim[i].header[columns[i].header.FIELD_DESC] = sim[i].header[Object.keys(sim[i].header)] } } console.log(sim);

Expected Output:

output = {
  "header": [{
      "Sales Organization": "1000",
      "Distribution Channel: "
      10 " 

    },
    {
      "Sales Organization": "1000",
      "Distribution Channel": "20"

    }
  ]
}

Is not perfect but try this

 let sim = { "header": [ { "VKORG": "1000", "VTWEG": "10" }, { "VKORG": "1000", "VTWEG": "20" } ] }; let columns = [ { "FIELD": "VKORG", "FIELD_DESC": "Sales Organization" }, { "FIELD": "VTWEG", "FIELD_DESC": "Distribution Channel" } ]; const filter = {}; for (let i = 0; i < columns.length; i++) { filter[columns[i].FIELD] = columns[i].FIELD_DESC; } sim.header = sim.header.map(el => { const keys = Object.keys(el); const newObj = {} for (const key of keys) { newObj[filter[key]] = el[key]; } return newObj; }); console.log(sim);

Here is an approach using Map and array.map. We store the columns as key value pair in Map, then while traversing the sim.header, just get the value from the map for the particular key and update it.

 let sim = { "header": [{ "VKORG": "1000", "VTWEG": "10" }, { "VKORG": "1000", "VTWEG": "20" } ] } let columns = [{ "FIELD": "VKORG", "FIELD_DESC": "Sales Organization" }, { "FIELD": "VTWEG", "FIELD_DESC": "Distribution Channel" } ] var map = new Map(); columns.forEach(obj => { map.set(obj.FIELD, obj.FIELD_DESC); }) sim.header = sim.header.map(obj => { var tempObj = {}; Object.keys(obj).forEach(key => { tempObj[map.get(key)] = obj[key] }) return tempObj; }) console.log(sim);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM