J.Doe J.Doe - 11 days ago 6
Javascript Question

How to match object key name with lodash?

I have two parent objects that serve different purposes.

enter image description here

Object 1 - Use to identify boolean value of that key

Object 2 - Contains real data to be used

What I'm trying to do: run matches on the names of both objects,

if item3(object1)'s name === item3(object2)'s name
if item3(object1) === true
item3(object2)'s value ++
else return;


Is it possible to get the object name and run comparisons? Or is there a better approach?

Answer

If I understand correctly what you're looking for, you want to increment the value in one of Object 2 sub objects, if it exists in Object 1, and it's true.

You can do so using Object.keys() to get an array of the keys, and then iterate it using Array.prototype.forEach():

Object.keys(Object2).forEach((key) => Object1[key] && (Object2[key] += 1));

const Object1 = { item2: false, item3: true, item5: true};
const Object2 = {
	item1: {
		name: 'PC',
		value: 0
	},
	item2: {
		name: 'Hackintosh',
		value: 0
	},
	item3: {
		name: 'MAC',
		value: 15.3
	},
	item4: {
		name: 'Linux',
		value: 0
	},
	item5: {
		name: 'Android',
		value: 11.4
	}	
};

Object.keys(Object2).forEach((key) => Object1[key] && (Object2[key].value += 1));

console.log(Object2);