我有三个数组。 Array1:字段,Array2:配置,Array3:defaultChartType
我需要将字段数组对象的“名称”属性与配置数组对象的“度量”进行比较。如果匹配,则配置对象应使用字段对象的标签更新。 如果配置对象中不存在字段中的任何名称属性对象,则应将其作为带有defaultchatType对象的新对象添加到配置数组中。
fields.map((measure) => {
let Measures = [];
Measures = config.map((k) =>
k.measures.map((val) => {
if (measure.name.indexOf(val) < 0) return null;
return k;
})
);
console.log(Measures, 'measuresmeasures');
return null;
});
var defaultChartType={
type:"line",
line: {
color: '#00ADFF',
width: 4,
},
}
var fields= [
{
name: ['Book1History','Book1Projected'],
label: 'Book1',
},
{
name: ['Book2Projected'],
label: 'Book2',
},
{
name: ['Book3History','Book3Projected'],
label: 'Book3',
},
{
name: ['Book4'],
label: 'Book4',
}
]
var config= [
{
measures: ['Book1History', 'Book1Projected'],
type: 'line',
},
{
measures: ['Book2Projected'],
type: 'bar',
},
]
var expectedOutput=[
{
"measures": [
"Book1History",
"Book1Projected"
],
"type": "line",
"label": "Book1"
},
{
"measures": [
"Book2Projected"
],
"type": "bar",
"label": "Book2"
},
{
"measures": [
"Book3History",
"Book3Projected"
],
"label": "Book3",
"type": "line",
"line": {
"color": "#00ADFF",
"width": "4"
}
},
{
"measures": [
"Book4"
],
"label": "Book4",
"type": "line",
"line": {
"color": "#00ADFF",
"width": "4"
}
}
]
答案 0 :(得分:1)
首先使用过滤器,并且如果配置measures
中的任何元素与names
相匹配,我都会从config中取出元素。
如果匹配项将从found
变量中删除类型,并且将其类型添加到输出(如果不添加默认类型的话)。
var defaultChartType={type:"line", line: { color: '#00ADFF',width: 4,},}
var fields= [{ name: ['Book1History','Book1Projected'], label: 'Book1', },{ name: ['Book2Projected'], label: 'Book2', }, { name: ['Book3History','Book3Projected'], label: 'Book3', }, { name: ['Book4'],label: 'Book4', } ]
var config= [{measures: ['Book1History', 'Book1Projected'],type: 'line',},{measures: ['Book2Projected'], type: 'bar', },]
let op = fields.map(ele=>{
let found = config.filter(({measures})=>{
return measures.every((el,index)=>{
return el === ele.name[index]
})
})
return{
...ele,
type: found.length ? found[0].type : defaultChartType
}
})
console.log(op)