How to access Json key inside a json key - javascript

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.

Related

how to get all the values inside JSON with a common name?

I need to get an array of all the name values from a JSON structure.
My JSON looks like this:
{
"profile": {
"G5j7": {
"name": "siddharth",
"age": "17"
},
"Loj9": {
"name": "ram",
"age": "20"
},
"Huy8": {
"name": "maix"
}
}
}
I can get a specific name value by:
var singleName = profile.G5j7.name;
But how do I get an array of all the name values if don't know all the IDs inside profile? I need to store in a variable.
const arrayName = Object.values(profile).map((item) => item.name);
You can use Object.getOwnPropertyNames. This function getting field names from in object to array.
let data = { "profile": { "G5j7": { "name": "siddharth", "age": "17" }, "Loj9": { "name": "ram", "age": "20" }, "Huy8": { "name": "maix" } } }
let propNames = Object.getOwnPropertyNames(data.profile)
propNames.forEach((propname) => { console.log(data.profile[propname].name) })
Object.values(yourObj.profile).map(v => v.name)
Object.values() returns an array of the values on every (own) prop of your object. So you can forget about the property names and iterate on its values
You can use Object.keys to get all properties keys in an Object, with that you can get access to all profile object keys with that you can retrieve name for each key like bellow
let data = {
"profile": {
"G5j7": {
"name": "siddharth",
"age": "17"
},
"Loj9": {
"name": "ram",
"age": "20"
},
"Huy8": {
"name": "maix"
}
}
};
let profiles_keys = Object.keys(data.profile);
let results = profiles_keys.reduce((accumulator, current)=> {
return accumulator.concat(data.profile[current].name)
}, []);
console.log(results);
let data = {
"profile":
{ "G5j7": { "name": "siddharth", "age": "17" },
"Loj9": { "name": "ram", "age": "20" },
"Huy8": { "name": "maix" }
}
};
for (const [key, value] of Object.entries(data.profile)) {
console.log(`${value.name}`);
}
You can do like this:
const names = Object.values(profile).map((profile) => profile.name);
Object.values() returns an array of the values.
Then for each profile, use .map() to get each name.
const decodedJsonObject = " { "profile": { "G5j7": { "name": "siddharth", "age": "17" }, "Loj9": { "name": "ram", "age": "20" }, "Huy8": { "name": "maix" } } }"
var singleName = profile.G5j7.name;

Look up values in an array using looping forEach Google Apps Script Javascript

I have an object that looks like the following {key: id numbers}
var obj = {
"c4ecb": {id: [3]},
"a4269": {id: [34,36]},
"d76fa": {id: [54,55,60,61]},
"58cb5": {id: [67]}
}
How do I loop each above id in the following array, and return the label?
var response =
{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}
Finally, what I want to do is look up the key and return a string of id values.
For example, input c4ecb and output strawberry. Input a4269 and output lettuce, radish. Input d76fa and output "spaghetti, rigatoni, lasagna, fettuccine"
I think to join the multiple labels output into one string I could use something like
array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();
So in the end I want to have something like
var fruits = [some code that outputs "strawberry"];
var vegetables = [some code that outputs "lettuce, radish"];
var pasta = [some code that outputs "spaghetti, rigatoni, lasagna, fettuccine"];
What I've tried so far:
The following loop will return the id only if there is one id to be called for: e.g. only in case one where {id: 3} but returns null in cases like {id: 34,36} (because it's looking for '34,36' in id, which doesn't exist - I need to look for each one individually.
response.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
Filter the response object to focus on the category that matches the id.
Map over the options array and select the items which appear in obj[id].
Finally convert the filtered results to a string.
See filteredLabelsAsString() function below for implementation.
var obj = {
"c4ecb": {"id": [3]},
"a4269": {"id": [34,36]},
"d76fa": {"id": [54,55,60,61]},
"58cb5": {"id": [67]}
}
var response =
[{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}];
function filteredLabelsAsString(obj_key, obj, content=response) {
// sanity check: obj must contain obj_key
if (Object.keys(obj).includes(obj_key)) {
return content.filter((item) => {
// filter content using value of obj_key
return item.data[0].key == obj_key;
}).map((item) => {
// item : { success: true, data: [] }
// map over options array
return item.data[0].options.map((opt) => {
// option : {id, label}
// return the label if the id is in the obj object's list
if (obj[item.data[0].key].id.includes(opt.id))
return opt.label;
}).filter((label) => {
// filter out empty items
return label !== undefined;
});
}).join(",");
}
// if obj does not contain obj_key return empty string
return "";
}
console.log("fruits: " + filteredLabelsAsString("c4ecb", obj));
console.log("vegetables: " + filteredLabelsAsString("a4269", obj));
console.log("pasta: " + filteredLabelsAsString("d76fa", obj));

How to insert a row in Javascript with a loop?

I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?
Json file:
{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
}
My code:
var jdata = {};
jdata.cols = [
{
"id": "1",
"label": "name",
"type": "string"
},
{
"id": "2",
"label": "country",
"type":"string"
}
];
for(var i = 1; i < 3; i++){
row = [
{
"c": [
{
"v": json["hits"]["hits"][i]["_source"]["name"]
},
{
"v": json["hits"]["hits"][i]["_source"]["country"]
}
]
}
];
jdata.rows.insertRow(row);
}
Edit: Add expected output: change the json file to the following structure.
[
['lily', 'china'],
['mike', 'japan'],
['lucy', 'korea'],
]
I guess you need push (Or concat / push(...elements) if you want to add array of rows)
jdata.rows = [];
for(var i = 1; i < 3; i++){
row = [
{
"c": [
{
"v": json["hits"]["hits"][i]["_source"]["name"]
},
{
"v": json["hits"]["hits"][i]["_source"]["country"]
}
]
}
];
jdata.rows.push(row);
// for elements from row
// jdata.rows.push(...row)
}
There are a few errors in your code
The JSON needs to be an array so you can loop through each object to display.
insertRow() is a method from the Table object, jdata.rows is not a Table object but an array.
Since, you have used insertRow(), I have rewritten your code to display the table data using the Table Object methods. Here is a code snippet
Edit: You can use the push() method to create your required JSON structure. I have edited the code snippet to create your required JSON.
var jdata = {
cols: [{
"id": "1",
"label": "name",
"type": "string"
},
{
"id": "2",
"label": "country",
"type": "string"
}
],
rows: []
};
var persons = [{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
}, {
"name": "lucy",
"country": "korea",
"age": 25
}
];
var table = document.getElementById("table");
var header = table.createTHead();
var footer = table.createTFoot();
var rowHeader = header.insertRow(0);
jdata.cols.forEach((col, index) => {
var cell = rowHeader.insertCell(index);
cell.innerHTML = col.label;
});
persons.forEach((person, index) => {
var rowFooter = footer.insertRow(index);
rowFooter.insertCell(0).innerHTML = person.name;
rowFooter.insertCell(1).innerHTML = person.country;
jdata.rows.push([person.name, person.country]);
});
console.log(jdata.rows);
<table id="table">
</table>

sort object by key by using lodash but key has lost after sorted

I want to sort some Object look likes this
data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
}
I want to sort it by "name".
I tried to use Lodash for this problem.
_.sortBy(data, [function(o) { return o.name; }]);
but, it return me an array of objects without the keys
[
{
"name": "Emmy",
"age": 20
},
{
"name": "Nacky",
"age": 12
},
{
"name": "Nat",
"age": 20
}
]
I want it return me sorted object with key like the same
{
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
}
what should I do? thanks
Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.
I can think of 2 options to work with that.
Add the key to the objects in the array
If you just need an ordered array with the keys in the objects, so you can render a list.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var result = _(data)
.map(function(v, k) { // insert the key into the object
return _.merge({}, v, { key: k });
})
.sortBy('name') // sort by name
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Create an order array
Create an array of ordered keys, and use them when you wish to render the objects in order.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var orderArray = _(data)
.keys() // create an array of keys
.sortBy(function(key) { // sort the array using the original names
return data[key].name;
}) // sort by name
.value();
console.log('The order array', orderArray);
console.log(orderArray.map(function(k) {
return data[k];
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
I use something like this.
let data = {
'g34ghgj3kj': {
YOUR_KEY: 'g34ghgj3kj',
'key1': false,
'key2': false,
},
'hh334h664': {
YOUR_KEY: 'hh334h664',
'key1': true,
'key2': false,
},
//{...}
};
_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
result[value.YOUR_KEY] = value;
return result;
}, {});

Compare two JSON Arrays and rearrange new JSON Array format

Here is the my first JSON Array format...
[
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
]
and here is another JSON Array Format
[
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
]
The above mentioned Two JSON Arrays, i need to compare each one with Id and need to format a new JSON Array with caption and value using javascript.
[
[
{
"caption" : "caption1",
"value":"value11"
},
{
"caption" : "caption2",
"value":"value12"
},
{
"caption" : "caption3",
"value":"value13"
}
],
[
{
"caption" : "caption1",
"value":"value21"
},
{
"caption" : "caption2",
"value":"value22"
},
{
"caption" : "caption3",
"value":"value23"
}
]
]
Please help me out.
You can do it in many ways. Below I show two variants:
Option 1: Pure JavaScript
In this example the program preindex first array for faster access to it data, and then loops over second array with map() function to create new array of arrays:
// Create index version of first array
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
// Loop over array of arrays
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
}
});
Option 2: Using special SQL library (Alasql)
Here, you can JOIN to arrays automatically with special SQL statement:
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] \
FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
You can try these variants in working snippet below or play with it in jsFiddle.
(Disclaimer: I am the author of Alasql)
var arr1 = [
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
];
var arr2 = [
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
];
// JavaScript version
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
});
});
document.getElementById("res1").textContent = JSON.stringify(res1);
// Alasql version
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
document.getElementById("res2").textContent = JSON.stringify(res2);
<script src="http://alasql.org/console/alasql.min.js"></script>
<p>Varian 1: JavaScript</p>
<div id="res1"></div>
<p>Variant 2: Alasql</p>
<div id="res2"></div>

Categories