首页 > 解决方案 > 如何提取值并创建一个新对象,如下所示

问题描述

我拥有的对象如下:

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 colorFilter = {
   red: ['tagA', 'tagC'],
   green: ['tagA', 'tagC'],
   blue: ['tagB'],
   yellow: ['tagC']
};

标签: javascript

解决方案


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)


推荐阅读