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 colorFilter = {
red: ['tagA', 'tagC'],
green: ['tagA', 'tagC'],
blue: ['tagB'],
yellow: ['tagC']
};
解决方案
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)
推荐阅读
- amazon-web-services - [亚马逊](500150) 错误设置/关闭连接:连接超时
- python - 尝试发送电子邮件附件时出错
- javascript - 处理对象数组时如何构造 GraphQL 突变
- python - 为什么 python 在 for 循环中击败 c++?
- java - 字节数组到带流的 int 数组
- arrays - 将浮点列表转换为字节数组并返回 Python
- nginx - 如何防止NGINX代理转发给自己
- arrays - 我想在更新条件后查看我的所有联系人列表
- python - 屏幕尺寸百分比作为在屏幕上找到一致点的方式,与分辨率无关
- javascript - 获取列值的总和,并且不允许在 UI 网格中添加新行