【发布时间】:2021-08-23 16:52:46
【问题描述】:
我已对 JSON 结构化 键值 对数据进行了无格式设置。我需要对其进行格式化并将其返回到另一个格式化的结构化.so中,
示例代码::
// Unformatted data like this, which contains repeating keys
let query = {
"junk,fruit,vegetable,junk,fruit": "pizza,apple,potato,burger,mango"
}
// formatting like this,
const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");
const newObj = {}
for (let i = 0; i < keys.length; i++) {
newObj[keys[i]] = values[i]
}
console.log(newObj)
//[ junk:pizza and fruit:apple are not returned in console]
//Output:
// {junk: 'burger',
// fruit: 'mango',
// vegetable: 'potato'}
JSON,不允许重复键,这就是它不返回的原因。这就是我试图在另一个结构中返回它的原因。
为此,如果 key 重复,则将其 value 推送到 same data of array 中,如预期输出所示。
newObj.includes('junk') 或 newObj.includes('mango'),通过它,可以检查该特定 key 是否已出现在输出中或数组中。
我想像这样返回我的输出:
{
'junk': {
'data': [
'pizza',
'burger'
]
},
'fruit': {
'data': [
'apple',
'mango'
]
},
'vegetable': {
'data': [
'potato'
]
}
}
JSFiddle 链接: https://jsfiddle.net/sophia22134/0yLxowt4/
【问题讨论】:
标签: javascript arrays json formatting