Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract values and create a new object as shown below

Tags:

javascript

The Objects I have are as below:

const tagA = {
  color: ['red', 'green'],
  type: { a: 10, b:7}...
};
const tagB = {
  color: ['blue', 'red'],
  type: { b:54, z:10} .... 
};
const tagC = {
  color: ['red', 'green', 'yellow'],
  type: { a: 13, b:17}...
};

I want to be able to create a new object like below:

const colorFilter = {
   red: ['tagA', 'tagC'],
   green: ['tagA', 'tagC'],
   blue: ['tagB'],
   yellow: ['tagC']
};
like image 462
kartik gavara Avatar asked Dec 11 '25 23:12

kartik gavara


1 Answers

const tagA = {color: ['red', 'green'],type: {a: 10,b: 7}}
const tagB = {color: ['blue', 'red'],type: {b: 54,z: 10}}
const tagC = {color: ['red', 'green', 'yellow'],type: {a: 13,b: 17}}
const tags = [tagA,tagB,tagC]
let colors = []
tags.forEach(t=>t.color.forEach(c=>colors.push(c)))
colors = colors.filter((c,i)=>colors.indexOf(c)===i)
let Color = {}
colors.forEach(c=>Color[c]=tags.filter(t=>t.color.includes(c)))
console.log(Color)
like image 184
holydragon Avatar answered Dec 13 '25 12:12

holydragon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!