js-nodejs对象和数组操作
在纠结数组和object之间关系的时候,总结如下:
假设两个对象
const obj1 = {
"tokenId": "1",
"uri": "ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/108",
"name": "美女11111",
"description": "很漂亮的美女1",
"ipfsImage": "https://gateway.ipfscdn.io/ipfs/QmVUK37rqCFfgTj5t1ZsJUbTGv4EgAtsSuCbZD6hPv9SkD/0"
}
const obj2 = {
"tokenId": "2",
"uri": "ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/109",
"name": "美女22222",
"description": "很漂亮的美女2",
"ipfsImage": "https://gateway.ipfscdn.io/ipfs/QmVUK37rqCFfgTj5t1ZsJUbTGv4EgAtsSuCbZD6hPv9SkD/1"
}
1.两个对象合并
const objA = {
obj1,obj2
}
console.log('objA:',objA)
打印结果如下:
objA: {
obj1: {
tokenId: '1',
uri: 'ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/108',
name: '美女11111',
description: '很漂亮的美女1',
ipfsImage: 'https://gateway.ipfscdn.io/ipfs/QmVUK37rqCFfgTj5t1ZsJUbTGv4EgAtsSuCbZD6hPv9SkD/0'
},
obj2: {
tokenId: '2',
uri: 'ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/109',
name: '美女22222',
description: '很漂亮的美女2',
ipfsImage: 'https://gateway.ipfscdn.io/ipfs/QmVUK37rqCFfgTj5t1ZsJUbTGv4EgAtsSuCbZD6hPv9SkD/1'
}
}
2.通过循环将未知长度的对象(数组)追加到数组中
let arrObj = []
for(const key of Object.keys(objA)){
let item = objA[key]
let obj = {}
obj.tokenId=item.tokenId+""
obj.uri=item.uri
obj.name=item.name
obj.description=item.description
obj.ipfsImage=item.image
// 添加对象到数组
arrObj.push(obj)
}
console.log('arrObj:',arrObj)
打印结果如下:
[
{
"tokenId": "1",
"uri": "ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/108",
"name": "美女11111",
"description": "很漂亮的美女1",
"ipfsImage": "https://gateway.ipfscdn.io/ipfs/QmVUK37rqCFfgTj5t1ZsJUbTGv4EgAtsSuCbZD6hPv9SkD/0"
},
{
"tokenId": "2",
"uri": "ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/109",
"name": "美女22222",
"description": "很漂亮的美女2",
"ipfsImage": "https://gateway.ipfscdn.io/ipfs/QmVUK37rqCFfgTj5t1ZsJUbTGv4EgAtsSuCbZD6hPv9SkD/1"
}
]
3.将数组对象转为json字符串
const jsonStr = JSON.stringify(arrObj)
console.log('arrObj:',jsonStr)
打印结果如下:
arrObj: [{"tokenId":"1","uri":"ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/108","name":"美女11111","description":"很漂亮的美女1"},{"tokenId":"2","uri":"ipfs://QmU98cczjKdTf9AqtbNXZikNE7vhLS5693ULXKocJ2vEoi/109","name":"美
女22222","description":"很漂亮的美女2"}]