Trouble Getting Basic JSON Values using Javascript - 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);

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

Append string to JSON array element in JS

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.

Value substitution while accessing nested json object

This is my json object
{
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
}
"c1" {
"field1": "name",
"field2": "status"
}
}
I need to access the value Tim by getting the field key within c1.
For example, I need to get the value of a1.c1.field1 which gives me the value name1 , then I need to access the value tim by a1.b1.(value of a1.c1.field1)
I do not know how to do this. Can someone give the possible ways to accomplish this?
var a1 =
{
"b1":
{
"name": "Tim",
"status": "Completed"
},
"c1":
{
"field1": "name",
"field2": "status"
}
};
console.log(a1.b1[a1.c1.field1]);
Do fix the error in your json too ;)
You can access using square brackets. With the data you provided,
var data = {
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
},
"c1":{
"field1": "name",
"field2": "status"
}
}
};
You can achieve your requirement by accessing.
data.a1.b1[data.a1.c1.field1]
Your JSON is a little off, so it's corrected below. This is an example of how to retrieve the value of field1 in the c1 object (in the a1 object)
$(document).ready(function () {
var json = {
"a1":
{
"b1":
{
"name": "Tim",
"status": "Completed"
},
"c1":
{
"field1": "name",
"field2": "status"
}
}
};
console.log(json.a1.b1.name); // returns Tim
// or
console.log(json["a1"]["b1"]["name"]); // returns Tim
});
Is this what you're looking for?
The obvious way is to use a1.c1.field1 as a property accessor using the bracket notation.
var obj = {
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
},
"c1": {
"field1": "name",
"field2": "status"
}
}
};
console.log(obj.a1.c1.field1); // 'name'
console.log(obj.a1.b1[obj.a1.c1.field1]); // 'Tim'
or, more legibly,
var key = obj.a1.c1.field1;
var value = obj.a1.b1[key];
console.log(value); // 'Tim'

How to access Json key inside a json key

I have a question regarding JSON. I am using a jquery plugin which expected JSON structure as below :
[ { key: "Id" },
{ key: "Username" },
{ key: "Age" }
],
but my JSON looks like :
[{
"Employee1":
{
"ID": 43036,
"Name": XYZ,
"Age": 21
},
"Employee2":
{
"ID": 30436,
"Name": MNP,
"Age": 23
}
}]
Now I don't want to change my code, is there any solution so that I can pass Id , Name to my plugin json without using "Employee".
I need my JSON as :
[
{
"ID": 43036,
"Name": XYZ,
"Age": 21
},
{
"ID": 30436,
"Name": MNP,
"Age": 23
}
]
Thanks in Advance
Something like this?
var myObj = [{
"Employee1":
{
"ID": 43036,
"Name": XYZ,
"Age": 21
},
"Employee2":
{
"ID": 30436,
"Name": MNP,
"Age": 23
}
}];
var jsonObj = [];
$.each(myObj[0], function(key, val){
jsonObj.push({ key: val.ID });
jsonObj.push({ key: val.Name });
jsonObj.push({ key: val.Age });
});
What you need a simple function to push the values inside the object,
var data = [{
"Employee1": {
"ID": 43036,
"Name": 'XYZ',
"Age": 21
},
"Employee2": {
"ID": 30436,
"Name": 'MNP',
"Age": 23
}}];
data = data[0];
var output = [];
for (i in data) {
output.push(data[i]);
}
DEMO
Note: The JSON you posted was invalid, XYZ and MNP are string values and I suppose the other numbers too.. I leave the validation to you.

Categories