Reputation: 2180
Hi I'm a beginner in javascript and trying to create a function that gets two objects as an argument, and in function, I want to create a new object which has keys of second object and value from the first object and if there's an extra key comes then will print same as it is in my created object
Output should be { Actor: "Programmer", firstName: "Bobo", shoeSize: 100 }
const obj = {
name: 'Bobo',
job: 'Programmer',
shoeSize: 100
};
const obj2 = {
name: 'firstName',
job: 'Actor'
}
function joinArray(data, data2){
var a={};
for(var key in data){
if(key in data2){
a{data2.key} = data{key}
} else {
a{data2.key} = data{key}
}
}
return a
}
console.log(joinArray(obj, obj2))
Upvotes: 0
Views: 429
Reputation: 22361
You can also do that
const obj = { name: 'Bobo', job: 'Programmer', shoeSize: 100 }
const obj2 = { name: 'firstName', job: 'Actor' }
function joinArray( data, keyNames)
{
let rep = {}
for (let k in data)
rep[((keyNames[k]) ? keyNames[k] : k)] = data[k]
return rep
}
console.log( joinArray(obj,obj2) )
.as-console-wrapper {max-height: 100%!important;top:0;}
OR:
const obj = { name: 'Bobo', job: 'Programmer', shoeSize: 100 }
const obj2 = { name: 'firstName', job: 'Actor' }
const joinArray = (data, keyNames) =>
Object.keys(data ).reduce((rep,k) =>
{
rep[((keyNames[k]) ? keyNames[k] : k)] = data[k]
return rep
},{})
console.log( joinArray(obj,obj2) )
.as-console-wrapper {max-height: 100%!important;top:0;}
Upvotes: 0
Reputation: 682
const obj = {
name: 'Bobo',
job: 'Programmer',
shoeSize: 100
};
const obj2 = {
name: 'firstName',
job: 'Actor'
}
function joinArray(data, data2) {
var a={};
for(var key in data) {
if(key in data2) {
a[data2[key]] = data[key]
} else {
a[key] = data[key]
}
}
return a
}
console.log(joinArray(obj, obj2))
This is the working example: https://jsfiddle.net/q4g8dpbm/1/
Upvotes: 2