Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a third object from two objects using the key values in JavaScript?
Suppose, we have two objects like these −
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
};
We are required to write a JavaScript function that takes in two such objects. The function should then use both these objects to calculate the positive and negative scores and return an object like this −
const output = {positive: 7, negative: 3};
Example
The code for this will be −
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
};
const findPositiveNegative = (obj1 = {}, obj2 = {}) => {
const result ={}
for (let key of Object.keys(obj1)) {
result[key] = obj1[key].reduce((acc, value) => {
return acc + (obj2[value] || 0);
}, 0)
};
return result;
};
console.log(findPositiveNegative(obj1, obj2));
Output
And the output in the console will be −
{ positive: 7, negative: 3 }Advertisements