Append string to JSON array element in JS - javascript

I have a specific format for a set of JSON objects. The format is as follows:
[{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}]
I am writing a function using simply JavaScript (no jQuery), that will append a value to the .value element based on if the user input matches a key value. For example, I input key2, the logic will match against key 2, and append "value7" to the end of the value element for that key, resulting in the following:
[{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6", "value7"]
}]
Currently the JSON is just an object in the JS file that is parsed using JSON.parse("string"). I would need to perform the appending and then rebuild the JSON using Stringify. (Assuming that would be my logic). I just need help with the appending because I am confused on the logic in this scenario. If anyone could throw together a quick example of how this would look in JS, that would be a massive help. Thank you!

You't target the object, and then the property containing the array, and push to that array
var array = [{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}];
array[1].value.push('value7');
console.log(array);

check this snippet
var arr = [{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}]
console.log(insertAtKey(arr, 2, "value7"));
function insertAtKey(arr, index, str) {
var obj = arr[index - 1];
Object.keys(obj).forEach(function(key, val) {
if (key === "value") {
obj[key].push(str);
}
});
arr[index - 1] = obj;
return arr;
}
Hope it helps

This question sounds like homework to me and I don't want to spoil the whole solution, but you can use a filter for searching in the object array, for adding the value you have the rest of the puzzle:
var data = [{
"key": ["key1"],
"value": ["value1", "value2", "value3"]
}, {
"key": ["key2", "key3"],
"value": ["value4", "value5", "value6"]
}];
function hasKey(k) {
return data.filter(e => { return e['key'].includes(k); });
}
console.log("for key1:" + hasKey("key1")[0].value);
console.log("for key2:" + hasKey("key2")[0].value);
console.log("for key3:" + hasKey("key3")[0].value);
What filter does:
e => { return e['key'].includes(k); } If the current object e in the data array includes a value k in the key attribute then pass the value.

Related

How to convert array object in snowflake

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.

Accessing data from an array in Javascript

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')

How to format string of JSON data obtained from Object.values in react?

I am trying to create a React accordion drop down menu that should display a list of entries that are grouped by each individual ID in the array. Each ID contains a list of thingsThatHaveChangedForThisId which can have multiple entries that consist of id, property, previousValue, and updatedValue The JSON data looks like this
[{
"id": "id1234",
"thingsThatHaveChangedForThisId": [{
"id": "id1234",
"property": "propertyValue",
"previousValue": "123",
"updatedValue": "456"
},
{
"id": "id1234",
"property": "propertyValue2",
"previousValue": "000",
"updatedValue": "001"
},
]
},
{
"id": "id456",
"thingsThatHaveChangedForThisId": [{
"id": "id456",
"property": "name",
"previousValue": "Anakin Skywalker",
"updatedValue": "Darth Vader"
},
{
"id": "id456",
"property": "lightsaberColor",
"previousValue": "blue",
"updatedValue": "red"
}
]
},
I used Object.values(data).map and was able to get a large string of thingsThatHaveChangedForThisId: id, property, previousValue, and updatedValue displaying in the drop down of each ID. The problem is that its just a string that is not grouped by individual entries. I would like to group each item in thingsThatHaveChangedForThisId so that when the dropdown is clicked, they are organized in groups of 4 rather than a large string. I have tried mapping over the keys of the JSON data and logging the result like so:
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
console.log(data[keys[i]]);
}
This gives me each item in the JSON object indexed by the keys. Which is almost what I want. I now need each item of the child array thingsThatHaveChangedForThisId grouped by the index so that I can make it a readable format. Something like:
Entries for id1234:
1. id: id1234
property: property
previousValue: previousValue
updatedValue: updatedValue
2. id: id1234
property: property2
previousValue: previousValue2
updatedValue: updatedValue2
3. id: id1234
property: property3
previousValue: previousValue3
updatedValue: updatedValue3
I can make it look nice once I have the data formatted correctly. I have also tried mapping over the values of data in the same manner but it throws error "each child should have a unique key prop". Which I thought they did as each child in the array is a key value pair. I think I am on the right track but I have been stuck for a while. Any help would be greatly appreciated! Thanks.
Something like this should work for you
const data = [{
"id": "id1234",
"thingsThatHaveChangedForThisId": [{
"id": "id1234",
"property": "propertyValue",
"previousValue": "123",
"updatedValue": "456"
},
//...
]
},
//...
];
let formattedData = [];
data.forEach(obj => {
/*
obj is:
{
"id": "id1234",
"thingsThatHaveChangedForThisId": [{
"id": "id1234",
"property": "propertyValue",
"previousValue": "123",
"updatedValue": "456"
},
//...
]
}
*/
obj.thingsThatHaveChangedForThisId.forEach(thing => {
/*
thing is:
{
"id": "id1234",
"property": "propertyValue",
"previousValue": "123",
"updatedValue": "456"
}
*/
formattedData.push({
id: obj.id,
property: thing.property,
previousValue: thing.previousValue,
updatedValue: thing.updatedValue,
});
});
});
//use formattedData

Trouble Getting Basic JSON Values using Javascript

I have a JSON object similar to this one
{
"x": [
{
"key": "value"
},
{
"key2": "value2"
}
]
}
And doing console.log(x[0].key) won't return 'value'. Instead I get an error saying that x is undefined.
Any ideas?
Thank you
You have to start with whatever is holding the object.
E.g.
var data = {
"x": [
{
"key": "value"
},
{
"key2": "value2"
}
]
};
console.log(data.x[0].key);
This should return 'value'.
var x = {
x: [{
"key": "value"
},
{
"key2": "value2"
}]
};
console.log(x['x'][0].key);

Format Array into new Array

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'));

Categories