问题描述
我有以下对象数组:
Newvar
如果它们具有相同的[
{ ip: 1,name: 'examplel' },{ ip: 1,{ ip: 202.164.171.184,name: 'example2' },name: 'example3' },{ ip: 127.0.0.1,name: 'example4' },name: 'example5' }
]
但不等于ip
,我想在它们上面放上颜色,就像这样。
name
如何使用lodash实现这一目标?还是香草?
编辑:我试图对它进行编码,但是产生了不同的输出。
[
{ ip: 1,name: 'examplel',color: '' },name: 'example2',color: 'red' },name: 'example3',name: 'example4',color: 'black' },name: 'example5',color: 'black' }
]
这是我的代码。
[
{ ip: 1,color: 'black' }
]
解决方法
在设置颜色之前,您可以尝试使用每个来检查list [key]的每个元素的名称和ip是否相同:
https://lodash.com/docs/4.17.15#every
let data = [
{ ip: '1',name: 'examplel' },{ ip: '1',{ ip: '202.164.171.184',name: 'example2' },name: 'example3' },{ ip: '127.0.0.1',name: 'example4' },name: 'example5' }
];
let list = _.groupBy(data,'ip')
const colorList = ['pink','blue','pink','red']
let logsList = []
console.log('list: ' + JSON.stringify(list));
_.keys(list).forEach(key => {
if (Array.isArray(list[key])) {
let color = '';
if(!_.every(list[key],list[key][0])) {
color = colorList[Math.floor(Math.random() * colorList.length)]
}
list[key].forEach(data => {
data.color = color
logsList.push(data)
})
}
})
console.log('logsList: ' + JSON.stringify(logsList));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
,
您的代码中的问题
一个问题可能是生成随机颜色:您可以两次获得颜色
固定代码:
let data = [ // Example data
{ ip: 1,{ ip: 1,'ip')
const colorList = ['pink','red'] // Color should not be in this list twice!
let logsList = []
_.keys(list).forEach(key => {
if(!colorList.length) throw new Error('Not enough colors');
let color = colorList[Math.floor(Math.random() * colorList.length)] // Chose color
colorList.splice(colorList.indexOf(color),1); // Remove chosen color from the list
// So,we cannot chos one color twice
// Removed not-needed IF
list[key].forEach(data => {
data.color = color
logsList.push(data)
})
})
console.log(logsList)
<!-- Get lodash -->
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
另一种可行的解决方案
未使用Lodash,是在未将代码添加到问题中时编写的。悲伤删除。
let datas = [
{ ip: 1,name: 'example5' }
];
let colors = ['green','red','purple',/* And some more... */]; // Colors for diffrent IP's
let currentColor = 0,// Which color we are currently using - index in colors[]
pastIp = null; // Past Ip
let colored = datas.sort((a,b) => ('' + a.ip).localeCompare(b.ip)) // Sort IP's,// Same adresses will be grouped
.map(i => {
if(pastIp && i.ip != pastIp) currentColor++; // We have started colorig another IP (as example,past was 1.1.1.1,this is 2.2.2.2)
// Else,we are looping same IP's (as example,this is also 1.1.1.1)
pastIp = i.ip; // Current will be past
return {color: colors[currentColor],...i}; // Add color property
})
console.log(colored); // Do somethig with result