[英]To place values of object from key value pair in an array in javascript
I have an object我有一个 object
{
"input":{
"id": "7879",
"inputType": "9876",
"streamName": "870"
},
"transformation":{
"id": "7",
"dependencies": [
"8i"
],
"dropColumns": "hkj",
"processor": "hgf"
},
"output": {
"id": "v",
"saveMode": "uyt",
"dependentIds": [
"h"
],
"outPartition":[
"hg"
]
}
}
Basically every value leaving the key I have to put it in an array.基本上每个离开键的值我都必须把它放在一个数组中。 So input, transformation, output values(which are objects) should be placed inside array.
所以输入、转换、output 值(它们是对象)应该放在数组中。
Expected Output:预期 Output:
{
"input": [
{
"id": "7879",
"inputType": "9876",
"streamName": "870"
}
],
"transformation":[
{
"id": "7",
"dependencies": [
"8i"
],
"dropColumns": "hkj",
"processor": "hgf"
}
],
"output":[
{
"id": "v",
"saveMode": "uyt",
"dependentIds": [
"h"
],
"outPartition":[
"hg"
]
}
]
}
I tried iterating using the for in loop but was not able to achieve the expected output how should I place the values(object) inside array我尝试使用 for in 循环进行迭代,但无法实现预期的 output 我应该如何将值(对象)放在数组中
var arr = [];
for(key in obj){
arr.push(Object.assign(obj[key],{name: key}))
}
You mean this (although not sure why you would need this)?你的意思是这个(虽然不确定你为什么需要这个)?
const input = { "input":{ "id": "7879", "inputType": "9876", "streamName": "870" }, "transformation":{ "id": "7", "dependencies": [ "8i" ], "dropColumns": "hkj", "processor": "hgf" }, "output": { "id": "v", "saveMode": "uyt", "dependentIds": [ "h" ], "outPartition":[ "hg" ] } } Object.keys(input).forEach(key => input[key] = [input[key]] ) console.log(input)
According to the output of the object you provided, a simple implementation of looping the elements and creating the keys as arrays can be:根据您提供的 object 的 output ,循环元素并创建密钥为 arrays 的简单实现可以是:
for(key in obj){
obj[key] = [obj[key]];
}
You could rebuild it using the reduce function if you want to do it immutable:如果你想让它不可变,你可以使用 reduce function 重建它:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
reduce()方法对数组的每个元素执行一个化简器 function(您提供),从而产生单个 output 值。
More info see: MDN Webdocs - reduce()
更多信息请参阅: MDN Webdocs - reduce()
const data = { "input":{ "id": "7879", "inputType": "9876", "streamName": "870" }, "transformation":{ "id": "7", "dependencies": ["8i"], "dropColumns": "hkj", "processor": "hgf" }, "output": { "id": "v", "saveMode": "uyt", "dependentIds": ["h"], "outPartition":["hg"] } }; const customFormat = (data) => Object.keys(data).reduce((object, key) => { object[key] = [data[key]]; return object }, {}); console.log(customFormat(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.