1

i have two different arrays one have keys and one have values i want to combine this two arrays and create new one?

var keys = [
  { keyName: "col1", DispName: "Column 1" },
  { keyName: "col2", DispName: "Column 2" },
];
var values = [
  { col1: "Elijah", col2: "Michealson" },
  { col1: "Jhon", col2: "wick" },
];

var mappedData = new Array(values.length);
mappedData.fill({});

for (let i = 0; i < values.length; i++) {
  for (let key of Object.keys(values[i])) {
    for (let j = 0; j < keys.length; j++) {
      if (key == keys[j]["keyName"]) {
        mappedData[i][keys[j]["DispName"]] = values[i][key];
      }
    }
  }
}

console.log(mappedData);

but i'm getting this output

[
    {
        "Column 1": "Jhon",
        "Column 2": "wick"
    },
    {
        "Column 1": "Jhon",
        "Column 2": "wick"
    }
]

Expected output:

[
        {
            "Column 1": "Elijah",
            "Column 2": "Michealson"
        },
        {
            "Column 1": "Jhon",
            "Column 2": "wick"
        }
    ]

what i'm doing wrong here? Thanks in advance

Ben Wainwright
  • 4,224
  • 1
  • 18
  • 36
  • 1
    `mappedData.fill({})` populates the array with N copies of the _same_ single object. Try removing this line and putting `mappedData[i] = {}` in the outer loop. – georg May 04 '21 at 11:43

1 Answers1

0

Don't make it unnecessarily complex by doing multiple things with nested loops, instead; as per "the clean code" do one thing per function so you may find your logical error easily ...

Check out code bellow, it may help ...

let keys = [{keyName:"col1", DispName:"Column 1"}, {keyName:"col2", DispName:"Column 2"}];
let values = [{col1:"Elijah", col2:"Michealson"}, {col1:"Jhon", col2:"wick"}]

let mappedData = [...values]

function findDispName(keyName) {
    for(let a = 0; a < keys.length; a++) {
        if(keys[a]["keyName"] == keyName) {
            return keys[a]["DispName"]
        }
    }
}

for(let i = 0; i < values.length; i++) {
    let objKeys = Object.keys(values[i])
    for(let j = 0; j < objKeys.length; j++){
        delete Object.assign(values[i], {[findDispName(objKeys[j])]: values[i][objKeys[j]] })[objKeys[j]]
    }
}

console.log(mappedData)
JeX
  • 95
  • 1
  • 10