带有属性+数组的Json对象,如何移动数组内的属性?
Posted
技术标签:
【中文标题】带有属性+数组的Json对象,如何移动数组内的属性?【英文标题】:Json object with attributes + array, how to move the attributes inside the array? 【发布时间】:2019-11-29 06:37:21 【问题描述】:有没有办法使用 javascript 实现这种 json 转换?
输入
"server":"S1",
"timestamp":"123456",
"data":[
"device":"D1", "price":"50",
"device":"D2", "price":"60",
"device":"D3", "price":"70"
]
输出
"data":[
"server":"S1", "timestamp":"123456", "device":"D1", "price":"50",
"server":"S1", "timestamp":"123456", "device":"D2", "price":"60",
"server":"S1", "timestamp":"123456", "device":"D3", "price":"70"
]
【问题讨论】:
到目前为止你做了什么? 【参考方案1】:假设您的输入对象是
var input =
"server":"S1",
"timestamp":"123456",
"data":[
"device":"D1", "price":"50",
"device":"D2", "price":"60",
"device":"D3", "price":"70"
]
您可以转换为预期的输出,
let output =
data:[]
input.data.forEach(transformfunction);
function transformfunction(value,index,array)
output.data.push(
"server":input.server,
"timestamp":input.timestamp,
"device":array[index].device,
"price":array[index].price
);
console.log(JSON.stringify(output));
我希望它有所帮助。
【讨论】:
这个答案适用于我没有使用任何 ES6 功能的所有浏览器!【参考方案2】:试试这个:
const data =
"server":"S1",
"timestamp":"123456",
"data":[
"device":"D1", "price":"50",
"device":"D2", "price":"60",
"device":"D3", "price":"70"
]
result = data: data.data.map(res=>(...res, ...'timestamp': data.timestamp, 'server': data.server ))
console.log(result);
【讨论】:
感谢@GhoulAhmed,您的回答很有帮助。以上是关于带有属性+数组的Json对象,如何移动数组内的属性?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 MySQL 中的 JSON 数组内的元素中提取特定属性的所有值?