我想将下面的对象数组转换为另一种形式(varname被忽略,因为它不是必需的,键和值用于生成输出形式)。任何线索将不胜感激
输入数组: [ { “ key”:“ string_U6”, “ value”:“ grandwagoneer”, “ varname”:“ pagenameplate” }, { “ key”:“ string_U13”, “ value”:“ 2021”, “ varname”:“年份” } ]
输出
[ { “ string_U6”:“ grandwagoneer” }, { “ string_U13”:“ 2021” } ]
答案 0 :(得分:3)
当问题询问如何在 snowflake 中转换数组对象时,我想分享Snowflake的实现方法:
-- SQL to create a sample table with data
create table sample_table (v variant )
as select parse_json(' [ { "key": "string_U6", "value": "grandwagoneer", "varname": "pagenameplate" },
{ "key": "string_U13", "value": "2021", "varname": "year" } ]');
-- query to parse the variant and create the array:
select ARRAY_AGG( OBJECT_CONSTRUCT(i.value:key::varchar, i.value:value::varchar) )
from sample_table,
lateral flatten ( sample_table.v ) i;
它将产生您想要的精确输出。
答案 1 :(得分:1)
您可以尝试如下使用map:
var input = [ { "key": "string_U6", "value": "grandwagoneer", "varname": "pagenameplate" }, { "key": "string_U13", "value": "2021", "varname": "year" } ];
var output = input.map(function(entry){
let obj = {};
obj[entry.key] = entry.value;
return obj;
});
console.log(output);