js处理想要得到数据结构
var obj1 = {name: {a: 1}}, obj2 = {age: 10, name: {b: 2}} // mergeOptions(obj1, obj2) => {age: 10, name: {a:1, b:2}}
相互转换 obj -> arr arr -> obj
var obj = { a:1, b:2, c:3, d:4 } // obj -> arr var r = Object.entries(obj).map(([value, text])=> ({text, value})) console.log(r) // arr -> obj var obj2 = r.reduce((pre, {text, value})=> (pre[value] = text, pre), {}) console.log(obj2)
例1
var arr = [ { date: "2018-01-10", time: "11:00" }, { date: "2018-01-10", time: "12:00" }, { date: "2018-11-27", time: "1:00、2:00", }, { date: "2018-11-27", time: "3:00、4:00" }, { date: "2018-01-10", time: "5:00" } ];
// 输出 [ { date: "2018-11-27", time: "1:00、2:00、3:00、4:00" }, { date: "2018-01-10", time: "5:00" } ]
----------------------------------------------------------------------------------------------------------
// 用一行代码搞定
var res = Array.from(arr.reduce((pre, cur) => pre.set(cur['date'], [...(pre.get(cur['date'])|| []), cur.time]), new Map))
.map(([date, arr]) => ({date, time: arr.join('、')}))
var res = arr.reduce((pre, cur)=> { let i = pre.findIndex(v=> v.date===cur.date) if(i>-1){ pre[i].time = [pre[i].time, cur.time].join('、') }else{ pre.push(cur) } return pre }, []) console.log(res)
// 同理 var arr = [{a:1, b:2}, {a:1, c:3}, {a:4, d:5}]
// 得到 [{a:1, b:2, c:3}, {a:4, d:5}]
var res = arr.reduce((pre, cur) => {
let i = pre.findIndex(v => v.a = cur.a)
if (i > -1) {
pre[i].c = cur.c
} else pre.push(cur)
return pre
}, [])
------------------------------------------------------------------------------------------------------------
var arr =[{a:1,b:2,c:2},{a:1,b:2,c:3},{a:2,b:3,c:2},{a:2,b:3,c:2},{a:1,b:4,c:2}];
// 得到 [{a: 1, b: 2, c: 5}, {a: 2, b: 3, c: 4}, {a: 1, b: 4, c: 2}]
var res = arr.reduce((pre, cur)=>{
let i = pre.findIndex(v=> v.a === cur.a && v.b === cur.b)
i > -1 ? pre[i].c = cur.c + pre[i].c : pre.push(cur)
return pre
}, [])
console.log(res)
----------------------------------------------------------------------------------------------------------------
两个数组比较,拿出相同数据跟不同数据
var arr1 = ["1", "2", "3", "5"]
var arr2 = [{id: "1"},{id: "2"},{id: "3"},{id: "4"}]
var map = new Map(arr2.map(v=> [v.id, v]))
var [res1, res2] = arr1.reduce(([res1, res2], cur)=>{
map.has(cur) ? res1.push(map.get(cur)) : res2.push(cur)
return [res1, res2]
}, [[], []])
console.log(res1, res2)
-----------------------------------------------------------
var a = [{ name: "May", age: 12, id: 1 }, { name: "Jone", age: 13, id: 5 }, { name: "May", age: 15, id: 6 }]
// 整成
var res = [
{
name: 'May',
list: [{name: 'May', age: 12, id: 1},{name: 'May', age: 15, id: 6}]
},
{
name: 'Jone',
list: [{name: 'Jone', age: 13, id: 5}]
}
]
var res = Array.from(a.reduce((pre, cur)=> pre.set(cur.name, [...(pre.get(cur.name)||[]), cur]), new Map)).map(([name, list])=>({name, list}))
console.log(res)
例2
var arr1 = [{id: 1,name: '小明'}, {id: 2,name: '小强'}]; var arr2 = [{id: 1,age: 10}, {id: 2, age: 20}]; // 输出 [{id: 1, name: '小明', age: 10}, {id: 2,name: '小强', age: 20}] ---------------------------------------------------------------------------------------------------------- var res = arr2.reduce((pre, cur)=> { let same = arr1.find(v=> v.id===cur.id) pre.push(Object.assign({}, cur, same)) return pre }, []) console.log(res)
----------------------------------------------------------------------------------------------------------
var res = Array.from([...arr1, ...arr2].reduce((pre, cur)=>pre.set(cur.id, Object.assign(pre.get(cur.id)||{}, cur)), new Map).values())
例3 统计数组中相同项出现的个数
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; var res = names.reduce((pre, cur)=> { pre[cur] = pre[cur] ? ++pre[cur] : 1 return pre }, {}) for(var i in obj){ console.log(i, obj[i]) } ------------------------------------ // 字符串中出现最多的字符 var str = 'lllfff2rasdf' var res = str.split('').reduce((pre, cur)=>{ pre[cur] = pre[cur] ? ++pre[cur] : 1 return pre }, {}) console.log(res)
例4 数组的降维 (多维嵌套数组转化为单个数组)
如 [11, 20, 30, [17, 18, [9, 8, [1, 2, 3]]]] 输出 [11, 20, 30, 17, 18, 9, 8, 1, 2, 3]
var arr = [11,20,30,[17,18,[9,8,[1,2,3]]]] var res = arr => arr.reduce((pre, cur)=> { Array.isArray(cur) ? pre.push(...res(cur)) : pre.push(cur) return pre }, []) console.log(res(arr)) // 递归实现: function flatten(arr){ var arr2=[] for(var i=0;i<arr.length;i++){ cur = arr[i] Array.isArray(cur) ? arr2.push(...flatten(cur)) : arr2.push(cur) } return arr2 } console.log(flatten([[0, 1,[6,7,8,9]], [2, 3], [4, 5]])) // 1.数组扁平化、2.去除其中重复数据、3.得到一个升序且不重复的数组 方法1:var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10] function flatten(arr){ let res = arr.reduce((pre, cur)=>{ Array.isArray(cur)?pre.push(...flatten(cur)):pre.push(cur) return pre }, []) return [...new Set(res)].sort((a,b)=>a-b) } console.log(flatten(arr)) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 方法2: var arr = [ [1, 2, 2], [3, 4, '5', 5], [6, 7, 8, 9, [11, 12, [12, '13', [14] ]] ], '10'] console.log([...new Set(arr.flat(Infinity))].sort((a,b)=>a-b))
例5 数组(对象)去重 + 多数组的合并去重
// 数组去重 var arr = [1,1,1,22,3,,4,4] var res = [...new Set(arr)] console.log(res) var arr = [1,1,1,22,3,4,4] var res = arr.filter((v, i, pre)=> pre.indexOf(v) === i) // 数组对象去重 var arr = [{a:1,b:2},{a:1,b:2},{a:3,b:1},{a:5,b:2},{a:3,b:1}];//对象数组 var res = arr.reduce((pre, cur)=>{ var i = pre.findIndex(v=>JSON.stringify(v)===JSON.stringify(cur)) if(i===-1){ pre.push(cur) } return pre }, [])
// 法2
map在set时候如果有之前的item项中key有相等,就不重复设置,利用这一特性达到去重
var res = Array.from(
arr.reduce((pre, cur)=>pre.set(JSON.stringify(cur), cur), new Map)
.values()
)
// 法3
new Set存储的value不能是相同
Array.from(new Set(arr.map(v => JSON.stringify(v)))).map(v=>JSON.parse(v)) === [...
new
Set(arr.map(e => JSON.stringify(e)))].map(e => JSON.parse(e))
// 法4
function
unique(arr, key) {
const map =
new
Map()
return
arr.filter((item) => !map.has(item[key] +
''
) && map.set(item[key] +
''
, 1))
}
// 多数组的合并去重 var arr1 = [1,2,3,4] var arr2 = [1,2,3,4,5,6] var res = [...new Set([...arr1, ...arr2])] console.log(res)
例6 代码正常运行
Array.prototype.multiply = function(){ return this.push(...this.map(v=>v*v)) } var a = [1,2,3,4,5] a.multiply() console.log(a) // [1,2,3,4,5,1,4,9,25]
例7 项目中遇到的数据结构
var data = { "ETH": { "PPTR": [{ "curno": "KRW", "price": null }, { "curno": "JPY", "price": null }, { "curno": "USD", "price": null }, { "curno": "CNY", "price": '1' }], "ETH": [{ "curno": "KRW", "price": null }, { "curno": "JPY", "price": null }, { "curno": "USD", "price": null }, { "curno": "CNY", "price": '5' }] }, "USDT": { "USDT": [{ "curno": "KRW", "price": null }, { "curno": "JPY", "price": null }, { "curno": "USD", "price": null }, { "curno": "CNY", "price": '10' } ] }, 'eoc':[] } var arr = [] for (let [key, val] of Object.entries(data)) { for(let [key1, val1] of Object.entries(val)){ val1.reduce((cur, pre)=>{ arr.push({chain: key, symbol: key1, ...pre}) }, []) } } console.log(arr)
例8 一段很溜的代码
var a = [ { key: "id",num: "111" }, { key: "age", num: "222" } ]; var b = [ { key: "age",initVal: "23"}, { key: "id",initVal: "001"} ] var merge = (a,b) =>[...a.concat(b).reduce((m, x) => m.set(x.key, Object.assign(m.get(x.key) || {}, x)), new Map()).values()] console.log(merge(a,b)) // 类似数组对象当中,如果有相同的key值,就把value值相加 var arr =[{key:'a',value:2},{key:'a',value:2},{key:'a',value:2},{key:'b',value:8}] var res = Array.from(arr.reduce((pre, cur)=> pre.set(cur.key, (pre.get(cur.key) || 0) + cur.value), new Map)).map(([key, value])=>({key, value})) ------------------------------------------------------ var data = [{ method:'fly', code:'1', count:1, },{ method:'fly', code:'1', count:2, }] let newData = Array.from(data.reduce((m, {method, code, count}) => { let k = `${method}:${code}` let x = m.get(k) || {method, code, count: 0} x.count += count return m.set(k, x) }, new Map()).values()) console.log(newData)
-----------------------
例9
// 字段描述 var field = [{ field: '服务器', display: 'host', visible: true, type: 'checkbox' }, { field: '部门', display: 'department', visible: true, type: 'input' }] // 原始list数据 var list = [{ id: 1, host: '1.1 .1 .1', department: '技术' }] // 期望得到的数据 var res = [{ id: 1, host: { field: '服务器', display: 'host', value: '1.1 .1 .1', visible: true, type: 'checkbox' }, department: { field: '部门', display: 'department', value: '技术', visible: true, type: 'input' } } ] var fieldMap = new Map(field.map(d => [d.display, d])) var result = list.map(x=>{ return Object.keys(x).reduce((pre, cur)=>{ pre[cur] = fieldMap.has(cur) ? {...fieldMap.get(cur), value: x[cur]} : x[cur] return pre }, {}) })
例10
var array1 = [ {currency: 'CNY', value: 1 }, {currency: 'USD', value: 2 } ] var array2 = [ {currency: 'CNY', value: 332 }, {currency: 'USD', value: 424 }, {currency: 'HK', value: 123 } ] // 得到 var res = [ {currency: 'CNY', value: 332 }, {currency: 'USD', value: 424 } ] --------------------------------------------------------- var res=array2.filter(x=> array1.some(v=> v.currency===x.currency)) ---------------------------------------------------------- var map = new Map(array1.map(x=>[x.currency, x])) var res=array2.reduce((pre, cur)=>{ map.has(cur.currency) && pre.push(cur) return pre }, []) console.log(res)
例子11
js随机一个8位数
var num = Array(8).fill(0).map(() => Math.floor(Math.random()*10)).join('')
---------------------------
// fill生成一个二维数组
let arr = Array.from(Array(3)).map(()=> Array(3).fill(0))
例子12
var arry = ["股票开户", "期贷开户", "基金定股", "我的股东户", "服务中心", "私人顾问", "股票分析", "华泰证券", "股票行情"]
var arry1 = ["股票开户", "期贷开户", "基金定股", "我的股东户", "服务中心", "股票分析", "股票行情"]
// 变成统计次数的集合{"股票开户": 2, "期贷开户": 2, ... , "华泰证券": 1} var col = [...arry, ...arry1].reduce((p, c) => ((p[c] = ~~p[c] + 1),p), {}); var arr = Object.keys(col).map(v => ({label: v, value: v, disabled: col[v] === 1 ? true : false}));
-------------------
var set = new Set(arry)
var result = Array.from(new Set(arry1))
.map(x => ({label: x, value: x, disabled: !set.delete(x)}))
.concat(Array.from(set).map(x => ({label: x, value: x, disabled: true})))
例子13
js扁平化json对象
var data =[ { 'Id': '1', 'Name': '教学素材管理', 'Pid': '0', 'id': '659354849B9A44AA9E2477223DF68C96', 'children': [ { 'Id': '4DDA93E00CD34E4D812EC1A9E10AA883', 'Name': '教学素材', 'Pid': '659354849B9A44AA9E2477223DF68C96', 'id': '4DDA93E00CD34E4D812EC1A9E10AA883', 'children': [ { 'Id': '6CD3A04CFBC1419F81E1A66BDC81F177', 'Name': '修改', 'Pid': '4DDA93E00CD34E4D812EC1A9E10AA883', 'id': '6CD3A04CFBC1419F81E1A66BDC81F177' }, { 'Id': 'B93352644544420782337BC41C0534A9', 'Name': '添加', 'Pid': '4DDA93E00CD34E4D812EC1A9E10AA883', 'id': 'B93352644544420782337BC41C0534A9' } ] }, { 'Id': '68F89C4E368048E699F3D7EDD69A86A7', 'Name': '测试试题', 'Pid': '659354849B9A44AA9E2477223DF68C96', 'id': '68F89C4E368048E699F3D7EDD69A86A7' }, { 'Id': 'CF31D0CA5BC34765A61909B296E470C6', 'Name': '问题任务', 'Pid': '659354849B9A44AA9E2477223DF68C96', 'id': 'CF31D0CA5BC34765A61909B296E470C6' } ] }, { 'Id': 'B85EAE5FAAC64790AC62FA288E87AEAC', 'Name': '基础数据管理', 'Pid': '0', 'id': 'B85EAE5FAAC64790AC62FA288E87AEAC', 'children': [ { 'Id': '134D7E54B9D041539940D29E24592DF4', 'Name': '专业设置', 'Pid': 'B85EAE5FAAC64790AC62FA288E87AEAC', 'id': '134D7E54B9D041539940D29E24592DF4' }, { 'Id': '2314DE1399484596A7440326E07590DB', 'Name': '专业管理', 'Pid': 'B85EAE5FAAC64790AC62FA288E87AEAC', 'id': '2314DE1399484596A7440326E07590DB' } ] } ]
function flatten (data) { return data.reduce((arr, {Id, Name, Pid, id, children = []}) => arr.concat([{Id, Name, Pid, id}], flatten(children)), []) }
例子14
找出两个数组当中不同的值
var a=[1,2,3,4,5],b=[2,3,4,6,7] var setA = new Set(a), setB = new Set(b) b.forEach(x => setA.delete(x)) a.forEach(x => setB.delete(x)) var c = Array.from(setA), d = Array.from(setB) console.log(c, d) // 或者 var a=[1,2,3,4,5],b=[2,3,4,6,7] var c = a.filter(x=> !b.includes(x)) console.log(c) var d = b.filter(x=>!a.includes(x)) --------------------------------
var aa={a:1,b:1}
var bb=[{a:1,b:1,c:1},{a:2,b:2,c:1},{a:3,b:3,c:1}]
var aKeys = Object.keys(aa)
var res = bb.find(b => aKeys.every(k => aa[k] === b[k]))
console.log(res)
例子15
var sourceList = [ {SupportProgramId: 1, Category: "AAA", SubCategory: "A-1"}, {SupportProgramId: 2, Category: "AAA", SubCategory: "A-2"}, {SupportProgramId: 3, Category: "AAA", SubCategory: "A-3"}, {SupportProgramId: 4, Category: "BBB", SubCategory: "B-1"}, {SupportProgramId: 5, Category: "CCC", SubCategory: "C-1"}, {SupportProgramId: 6, Category: "CCC", SubCategory: "C-2"} ]; var data = Array.from(sourceList.reduce((map, {SupportProgramId: subId, Category: mainTitle, SubCategory: subTitle})=>{ if(map.has(mainTitle)) { map.get(mainTitle).subList.push({subId, subTitle}) } else map.set(mainTitle, {mainTitle, subList: [{subTitle, subTitle}]}) return map }, new Map).values()) console.log(data) -------------------------------------------- var arr = [ {id: 1, matter: 'xxx', current: '2018-10-31 09:30:00', photo: ['xxx', 'xxx']}, {id: 2, matter: 'xxx', current: '2018-10-31 11:30:00', photo: ['xxx', 'xxx']}, {id: 3, matter: 'xxx', current: '2018-10-30 08:47:00', photo: ['xxx', 'xxx']} ] Array.from( arr.reduce((m, x) => { const [date, time] = x.current.split(' ') const list = m.get(date) || [] list.push({ time: time.slice(0, -3), matter: x.matter, photo: x.photo }) return m.set(date, list) }, new Map()) ) .map(([date, list]) => ({ date, list: list.sort((a, b) => a.time > b.time ? 1 : a.time < b.time ? -1 : 0) })) .sort((a, b) => a.date > b.date ? -1 : a.date < b.date ? 1 : 0)
例子16
取 -20~-10 和 10~20 这两个范围的随机数
var res = (Math.floor(Math.random() * (20 - 10 + 1)) + 10) * (Math.random() < 0.5 ? -1 : 1) console.log(res)
例子17
var userToSkill = { robert: ["programming", "design", "reactjs"], kimia: ["java", "backend", "services"], patrick: ["reactjs"], chris: ["reactjs", "programming"] }; var obj = {} for(const [k, v] of Object.entries(userToSkill)){ for(const v2 of v) { obj[v2] ? obj[v2].push(k) : obj[v2] = [k] } } console.log(obj)