记录js中对象、数组
对象
{
infrastructure: 21,
wallet: 3,
dapp: 19,
explorer: 4,
social: 3,
tooling: 4,
defi: 11,
nft: 5,
dex: 3,
community: 5,
work: 3,
game: 3
}
对于对象的取值:
for (let tag in tags) {
console.log(tags[tag])
}
json格式
[
{
"id": "dl",
"title": "Departure Labs",
"url": "https://github.com/DepartureLabsIC/non-fungible-token",
"tags": "Dapp,NFT",
"website": "https://github.com/DepartureLabsIC/non-fungible-token",
},
{
"id": "axon",
"title": "Axon",
"url": "https://axon.ooo/",
"tags": "Infrastructure",
"website": "https://axon.ooo/",
}
]
js引入json文件(这只是一种)
const fs = require('fs')
const path = require('path')
try {
const projectfile = path.resolve(__dirname, '../data/projectData.json')
const projectDataContent = fs.readFileSync(projectfile)
projectData = JSON.parse(projectDataContent)
} catch (error) {
console.log(error)
}
遍历json,将tags全部取出,放到一个数组里。
let alltags = []
projectData.forEach((data) => {
if (data) {
alltags = alltags.concat(data.tags.split(','))
}
})
取出的alltags:
[
'Infrastructure', 'Infrastructure', 'Infrastructure', 'Infrastructure',
'Wallet', 'Infrastructure', 'Wallet', 'Dapp',
'Infrastructure', 'Explorer', 'Infrastructure', 'Explorer',
'Infrastructure', 'Explorer', 'Infrastructure', 'Explorer',
'Dapp', 'Social', 'Dapp', 'Social',
'Infrastructure', 'Tooling', 'DeFi', 'Dapp',
'NFT', 'DeFi', 'DeFi', 'Dex',
'Infrastructure', 'DeFi', 'DeFi', 'DeFi',
'Dex', 'DeFi', 'DeFi', 'DeFi',
'Infrastructure', 'Dapp', 'Tooling', 'Infrastructure',
'Dapp', 'Dapp', 'Tooling', 'Infrastructure',
'Community', 'Community', 'Community', 'Community',
'Community', 'Dapp', 'Work', 'Dapp',
'Work', 'Infrastructure', 'Infrastructure', 'Dapp',
'Work', 'Dapp', 'Social', 'Dapp',
'Game', 'Dapp', 'Game', 'Dapp',
'Game', 'Dapp', 'NFT', 'Dapp',
'NFT', 'Dapp', 'NFT', 'Infrastructure',
'Infrastructure', 'Wallet', 'Dapp', 'NFT',
'Dapp', 'DeFi', 'Infrastructure', 'Tooling',
'DeFi', 'Dex', 'Infrastructure', 'Infrastructure'
]
数组
统计数组中各个元素出现的个数。
var total = alltags.reduce((obj, name) => {
const lowerName = name.toLowerCase()
if (lowerName in obj) {
obj[lowerName]++
} else {
obj[lowerName] = 1
}
return obj
}, {})
console.log(total)
return total
}
|