【问题标题】:Json object with attributes + array, how to move the attributes inside the array?带有属性+数组的Json对象,如何移动数组内的属性?
【发布时间】: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"}
]
}

【问题讨论】:

  • 到目前为止你做了什么?

标签: javascript json


【解决方案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,您的回答很有帮助。
猜你喜欢
  • 2022-12-17
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多