-1

I'm learning javascript and have fiddled with this for ages and can't get the desired output

I've searched stack overflow and can not for the life of me adapt any other answer to do what I need it to do, keep getting undefined

var fruit = {apple:"red",graps:"purple"}
var vegetable = {cucamber:"green",lettuce:"green"}

var all_food = myFunction(fruit,vegetable);

want to return

{apple:"red",graps:"purple",cucamber:"green",lettuce:"green"}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Jake
  • 17
  • 5

2 Answers2

0

You can use spread syntax

const fruit = {
  apple: "red",
  graps: "purple"
}
const vegetable = {
  cucamber: "green",
  lettuce: "green"
}

const myFunction = (fruit, vegetable) => {
  return { 
    ...fruit,
    ...vegetable
  }
}
const allFood = myFunction(fruit, vegetable);

console.log(allFood)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Thanks so much, that worked perfectly, I was putting my function at the bottom which was giving me the undefined error. – Jake Aug 22 '19 at 05:17
0

There are two ways of doing it.

1- You can use Object spread operator .

function myFunction(obj1, obj2) {
    return {...obj1, ...obj2};
}

2- You can use Object.assign()

function myFunction(obj1, obj2) {
    return Object.assign(obj1, obj2);;
}