I would like to convert the below array of objects into another form (varname is ignored as its not required, key and value is used to generate the output form). Any leads would be appreciated
Input array:
[
{
"key": "string_U6",
"value": "grandwagoneer",
"varname": "pagenameplate"
},
{
"key": "string_U13",
"value": "2021",
"varname": "year"
}
]
Output
[
{
"string_U6": "grandwagoneer"
},
{
"string_U13": "2021"
}
]
You could try using map as below:
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);
As the question asked how to convert array object in snowflake, I wanted to share Snowflake way to do it:
-- 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;
It will produce exact output you want.
Related
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 1 year ago.
I need to convert JSON object to javascript array. This my object
var object =
[
{
"Key": "2019",
"value": 3
},
{
"Key": "2020",
"value": 3
},
{
"Key": "2021",
"value": 3
}
]
i need to weel be my array like this ['2019','2020','2021']
i try to to this
var data_t = [];
for (var i in object ) {
data_t.push(object );
}
console.log(data_t[0]);
But not working !!
You can use .map() for this:
var object = [
{
"Key": "2019",
"value": 3
},
{
"Key": "2020",
"value": 3
},
{
"Key": "2021",
"value": 3
}
];
console.log(object.map(a => a.Key));
var data_t = [];
for (var i in object ) {
data_t.push(i.Key);
}
I have the following Json Object
[
{ "key": "age", "value": 81 },
{ "key": "name", "value": "Luis" }
]
I am trying to find the most optimal way to recover this data.
const name = ??????;
What's the best way to extract the "value" of the 'name' key using Javascript? I know one of the ways would be to iterate until I find the value, but I figured there is a more fancy way, perhaps using filter?
Luis
I am assuming you need the object that has key as name
You can get use of find method
let array = [
{ "key": "age", "value": 81 },
{ "key": "name", "value": "Luis" }
]
let your_obj = array.find(element=>element.key === 'name')
console.log(your_obj) // this will give you the object you need
This will give results with key name
names = [
{ "key": "age", "value": 81 },
{ "key": "name", "value": "Luis" }
]
result = names.filter(name => name.key === 'name')
I have a JSON in the following format and need to convert the 2 values into a Key / Value pair in javascript
"column_values": [
{
"id": "status",
"text": "Working on it"
}
]
I need the result to be
"column_values"[{"status": "Working on it"}]
I need the code to iterate through the column_values array and convert all the sets of id and text pairs to the key = id value : Value = text:values
Is my result possible?
Additional Information...
I am parsing a response from monday.com api in zapier.
the api payload is contained in
const results = response.json;
the full api payload is
{
"data": {
"boards": [
{
"name": "Test Board",
"items": [
{
"name": "Name Change",
"id": "625495642",
"column_values": [
{
"id": "person",
"text": ""
},
{
"id": "subitems",
"text": "Subitem 1, Subitem 2"
},
{
"id": "status",
"text": "Working on it"
},
{
"id": "dropdown",
"text": "Test1"
},
{
"id": "formula",
"text": ""
}
]
}
]
}
]
},
"account_id": 1111
}
I need to the the code to parse the data and replace the column_values with the format above, and then pass the reformated payload to
return results;
You just Map the Array you start out with to an Array with the values.
var column_values = [ { "id": "status", "text": "Working on it" } ]
var KeyValuePairs = column_values.map(cv => [cv.id,cv.text]);
console.log(KeyValuePairs);
If every object is going to contain the id and text keys only, you can map it and delete the other keys.
column_values = column_values.map(item => {
item[item.id] = item.text;
delete item.id;
delete item.text;
return item;
});
try this
var column_values = [ { "id": "status", "text": "Working on it" } ]
var res = column_values.map(x => ({[x.id] : x.text}))
console.log(res)
Summary
I receive a large JSON object in node--about 10000 lines--from an external API and I'm creating a new, consolidated javascript object with the data I want.
I'm extracting specific key:value pairs from an object, where another key:value pair in the object matches what I'm looking for. The main issue I'm having is that if there is no data for a specific object, that object is not included and the function I wrote to assign the specific data I want to a variable becomes undefined and crashed my node server.
**Example API Response (Abbreviated) **
I commented on the data I'm trying to extract
{
"ApiJSONObject": {
"id": "t4365qewsagsdga4",
"stats": [{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 6435, //Extract this value and save to specific key in new javascript object
"displayValue": "6,435"
}
],
"segments": [{
"metadata": [{
"key": "segment",
"name": "Segment",
"value": "br.close_solo.season",
"displayValue": null
},
{
"key": "lastPlayedAt",
"name": "Last Played At",
"value": "2018-12-11T16:46:35Z",
"displayValue": "12/11/18 4:46:35 PM"
},
{
"key": "updatedAt",
"name": "Updated At",
"value": "2019-06-10T19:07:00.9143166Z",
"displayValue": "6/10/19 7:07:00 PM"
}
],
"stats": [{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 1, //extract this value and save to specific key in new javascript object based on metaData[0].value
"displayValue": "1"
},
{
"metadata": {
"key": "matchesPlayed",
"name": "Matches Played",
"isReversed": false
},
"value": 1,
"displayValue": "1"
}
]
}]
}
}
Current Function
I wrote this function, however it breaks my code as stats is undefined if there is no data for that specific statsSegment
function getSegmentStats(statType, playerStats) {
let filteredMetaData = [];
for (var i = 0; i < playerStats.segments.length; i++) {
filteredMetaData = playerStats.segments[i].metadata.filter(
val => val["value"] === statType
);
if (filteredMetaData.length) {
return playerStats.segments[i];
}
}
}
function getStatsFields(value,"br.close_solo.season") {
const stat = statsSegment.stats.find(x => x.metadata.name === value);
return stat.value;
}
const seasonSolo = getSegmentStats("br.close_solo.season", playerStats);
const statsObject = { seasonStats: seasonSolo: getStatsFields("Kills", seasonSolo))
The simplest solution would be to just check if your statsSegment is undefined at the start of your function, but first you need to decide what you do in case it is undefined.
you have few options:
throw an error
return an "errored" value- 0, false, -1- something that will never get returned as stat.value and you'll know for sure it means an error.
emit an event of some sort (don't know the context you're using this).
To perform the check simply add if(statSegment === undefined) at the start of getStatField function.
Also, i'd suggest you look at the docs for that 3rd party API you're using and see what undefined return value even means.
And one last thing- this API might return an empty object (also, check at the docs), so the undefined test will pass but you still won't be able to process the data. You can add an empty object test as well:
if(statSegment === undefined || (Object.entries(statSegment).length === 0 && statSegment.constructor === Object));
if you're using ECMA 7+, or:
if(statSegment === undefined || (Object.keys(statSegment).length === 0 && statSegment.constructor === Object));
if you're using ECMPA 5+.
(for more info about this empty object check go here)
When .find() can't find anything which matches its inner function's criteria, it will by default return undefined. By using the logical OR operator (||) you can set the value of stat to be a default object which always has a value of 0:
function getStatsFields(value,"br.close_solo.season") {
const stat = statsSegment && statsSegment.stats.find(x => x.metadata.name === value) || {value: 0};
return stat.value;
}
let statsSegmentJson = {
"ApiJSONObject": {
"id": "t4365qewsagsdga4",
"stats": [{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 6435, //Extract this value and save to specific key in new javascript object
"displayValue": "6,435"
}
],
"segments": [{
"metadata": [{
"key": "segment",
"name": "Segment",
"value": "br.close_solo.season",
"displayValue": null
},
{
"key": "lastPlayedAt",
"name": "Last Played At",
"value": "2018-12-11T16:46:35Z",
"displayValue": "12/11/18 4:46:35 PM"
},
{
"key": "updatedAt",
"name": "Updated At",
"value": "2019-06-10T19:07:00.9143166Z",
"displayValue": "6/10/19 7:07:00 PM"
}
],
"stats": [{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 1, //extract this value and save to specific key in new javascript object based on metaData[0].value
"displayValue": "1"
},
{
"metadata": {
"key": "matchesPlayed",
"name": "Matches Played",
"isReversed": false
},
"value": 1,
"displayValue": "1"
}
]
}]
}
};
let value = 'Kills';
function getStatsFields(value, statsSegment) {
let statsSegmentStr = JSON.stringify(statsSegment);
let statsSegmentObj = JSON.parse(statsSegmentStr);
console.log("statsSegment", statsSegmentObj);
console.log("statsSegment.stats ", statsSegmentObj.ApiJSONObject.stats);
const stat = statsSegmentObj.ApiJSONObject.stats.find(x => x.metadata.name === value);
if (stat) {
return stat.value;
}
}
let result = getStatsFields(value,statsSegmentJson);
console.log(result);
I have an array of objects. I would like to reformat into a new array but am not sure how to begin. I have jQuery and Underscore available.
Here is my original array:
var myArray = [
{
"name": "Product",
"value": "Car"
},
{
"name": "Product",
"value": "Boat"
},
{
"name": "Product",
"value": "Truck"
},
{
"name": "Color",
"value": "Blue"
},
{
"name": "Location",
"value": "Store"
}
];
Here is what I am trying to make the new Array look like:
var newArray = [
{
"name": "Product",
"value": "Car Boat Truck"
},
{
"name": "Color",
"value": "Blue"
},
{
"name": "Location",
"value": "Store"
}
];
In the newArray the Products are all in one object.
You can use the groupBy method to get all the elements with the same name together, then map to transform them into what you want. And pluck is useful here to combine the values in the output array.
Here's quick, simple solution:
var newArray = _.chain(myArray)
.groupBy("name")
.map(function(a) {
return {
"name": a[0].name,
"value": _.pluck(a, "value").join(" ")
};
})
.value();
Demonstration
And just for completeness, here's the non-chained version:
var newArray = _.map(_.groupBy(myArray, "name"), function(a) {
return {
"name": a[0].name,
"value": _.pluck(a, "value").join(" ")
};
});
Here's a more generalized solution that's reusable and not hard-coded. This way, you can create multiple groupBy methods for different properties of different object collections, then join the properties that you require. jsFiddle
function groupBy(groupBy) {
return function(source, joinOn) {
return _.each(_.groupBy(source, groupBy), function(val, key, context){
context[key] = _.pluck(val, joinOn).join(' ');
});
};
}
var groupByNameOn = groupBy('name');
console.log(groupByNameOn(arr, 'value'));