Retrieving Keys from JSON Array key-value pair dynamically - Javascript
Are you using D3.js as your tag implies? Because in that case, you can just use d3.keys()
:
var data = [{"A":20,"B":32,"C":27,"D":30,"E":40}];
d3.keys(data[0]); // ["A", "B", "C", "D", "E"]
If you want the sum of all the values, you might be better off using d3.values()
and d3.sum()
:
var data = [{"A":20,"B":32,"C":27,"D":30,"E":40}, {"F":50}];
// get total of all object totals
var total = d3.sum(data, function(d) {
// get total of a single object's values
return d3.sum(d3.values(d));
});
total; // 199
Angular 2 get key and value from json array with dynamic key
In your example, you have an array of objects and each of these object has exactly one property.
for (let obj of arr) {
console.log("object:", obj);
for (let key in obj) {
console.log(" key:", key, "value:", obj[key]);
}
}
The following code from your posting
for (let key in arr) {
console.log ('key: ' + key + ', value: ' + arr[key]);
}
... would work on a data structure like this:
let arr = {
key1: 'val1',
key2: 'val2',
key3: 'val3'
};
Dynamically accessing the key value pair in Javascript
Object.keys is supported in safari.
var data = {
"http": {
"method": "POST",
"headers": [{"content-type": "application/json" },{ "Authorization": "KKYZASSHUYTRJ"}],
"url": "http://localhost:8888/download/context"
}
}
data["http"]["headers"].forEach(entry => console.log(Object.keys(entry)[0], entry[Object.keys(entry)[0]]))
JavaScript iterate key & value from json?
Use Object.keys()
to get keys array and use forEach()
to iterate over them.
var data = {
"VERSION": "2006-10-27.a",
"JOBNAME": "EXEC_",
"JOBHOST": "Test",
"LSFQUEUE": "45",
"LSFLIMIT": "2006-10-27",
"NEWUSER": "3",
"NEWGROUP": "2",
"NEWMODUS": "640"
};
Object.keys(data).forEach(function(key) {
console.log('Key : ' + key + ', Value : ' + data[key])
})
How to dynamically change JSON key (including its children keys) in Javascript?
One possible way to do it is to re write the keys into a new object like this:
let obj = {};
let o = { "DR.No":1, "foo": 2 };
let keys = Object.keys(o);
for(let i = 0;i < keys.length;i++) {
let key = keys[i];
obj[key.replace(".",",")] = o[key]
}
JSON.stringify(obj,null,2)
"{
"DR,No": 1,
"foo": 2
}"
Or if there are many dots:
let obj = {};
let o = { "DR.No.Blah.Dots.ToMany":1, "Weird.Dots.In.Keys": 2 };
let keys = Object.keys(o);
for(let i = 0;i < keys.length;i++) {
let key = keys[i];
let originalKey = key;
key = key.split(".").join(",");
obj[key] = o[originalKey]
}
JSON.stringify(obj,null,2)
"{
"DR,No,Blah,Dots,ToMany": 1,
"Weird,Dots,In,Keys": 2
}"
If you want the keys to not have punctuation in them get rid of the commas....
....in answer to your comment here is one possible way to do it. Taking a sample from the json data in your question:
var data = [
{
"address": "0xde083e40fe84835cbbd6c69f6595cae1e85551dc",
"name": "Ledger Legend Cards",
"symbol": "LLC",
"image_url": "https://storage.googleapis.com/opensea-static/ledgerlegends-logo.png",
"featured_image_url": null,
"featured": false,
"description": "Ledger Legends is an early access collectible card game built on the Ethereum platform. It uses the new ERC721 non-fungible token standard to track its cards. Using this standard makes it easy for the cards to integrate into the wider Ethereum ecosystem, like exchanges and wallets. Being a card game that is built using smart contracts you know that your cards will always be owned by you and can never be taken away by anyone unlike centralized games such as Hearthstone.",
"external_link": "https://ledgerlegends.com/",
"wiki_link": null,
"stats": {
"seven_day_volume": 0,
"seven_day_change": 0,
"total_volume": 0,
"count": 282,
"num_owners": 54,
"market_cap": 0,
"average_price": 0,
"items_sold": 0
},
"traits": [
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
},
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
},
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
},
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
"MORE.MORE.MORE": [
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
},
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
},
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
},
{
"FN.RA.NA": "Value A",
"RR.TT.DD": "Value B",
}
]
}
],
"hidden": true,
"nft_version": "1.0",
"schema_name": "ERC721",
"display_data": {
"images": [
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png"
]
},
"short_description": null,
"total_supply": null,
"owner": null,
"buyer_fee_basis_points": 0,
"seller_fee_basis_points": 250
}
];
//is it an object
function isObject(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}
//is it an array
function isArray(o) {
return Array.isArray(o);
}
//clean the keys and take advantage of the reference to the original
//object to re write and replace the keys and their values
function cleanKeys(o) {
var keys = Object.keys(o);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var toCheck = o[key];
var originalKey = key;
//if there is a dot in the key
//re write it and replace it
if (key.indexOf('.') > -1) {
key = key.split(".").join(",");
o[key] = o[originalKey];
delete o[originalKey];
}
if (isArray(toCheck) || isObject(toCheck)) {
removeDots(toCheck);
}
}
}
//a somewhat recursive function with bits broken out for readability
function removeDots(obj) {
switch (Object.prototype.toString.call(obj)) {
case "[object Array]":
for (var i = 0; i < obj.length; i++) {
var o = obj[i];
if (isArray(o)) {
removeDots(obj);
} else {
cleanKeys(o);
}
}
break;
case "[object Object]":
cleanKeys(obj);
break;
}
}
removeDots(data);
console.log(JSON.stringify(data, null, 2));
[
{
"address": "0xde083e40fe84835cbbd6c69f6595cae1e85551dc",
"name": "Ledger Legend Cards",
"symbol": "LLC",
"image_url": "https://storage.googleapis.com/opensea-static/ledgerlegends-logo.png",
"featured_image_url": null,
"featured": false,
"description": "Ledger Legends is an early access collectible card game built on the Ethereum platform. It uses the new ERC721 non-fungible token standard to track its cards. Using this standard makes it easy for the cards to integrate into the wider Ethereum ecosystem, like exchanges and wallets. Being a card game that is built using smart contracts you know that your cards will always be owned by you and can never be taken away by anyone unlike centralized games such as Hearthstone.",
"external_link": "https://ledgerlegends.com/",
"wiki_link": null,
"stats": {
"seven_day_volume": 0,
"seven_day_change": 0,
"total_volume": 0,
"count": 282,
"num_owners": 54,
"market_cap": 0,
"average_price": 0,
"items_sold": 0
},
"traits": [
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
},
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
},
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
},
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B",
"MORE,MORE,MORE": [
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
},
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
},
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
},
{
"FN,RA,NA": "Value A",
"RR,TT,DD": "Value B"
}
]
}
],
"hidden": true,
"nft_version": "1.0",
"schema_name": "ERC721",
"display_data": {
"images": [
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png",
"https://ledgerlegends.com/img/monster.png"
]
},
"short_description": null,
"total_supply": null,
"owner": null,
"buyer_fee_basis_points": 0,
"seller_fee_basis_points": 250
}
]
how to get data from dynamic key pair value in Angular
That is because of the +
before the value
, which will try to concatenate the value and you will see [object object]
var d = { "pexels-photo.jpeg": { "information": "laptop", "desc": { "mimetype": "image/jpeg", "id": "shsj44", "file_id": "pexels-photo.jpeg" }, "_id": "shsj44" }}
Object.keys(d).forEach(function(key) { let value = d[key]; console.log(key + ' : ', value); console.log(key + ' : ', value.desc.id);});
Related Topics
Using JavaScript to Detect Whether the Url Exists Before Display in Iframe
Check Whether an Input String Contains a Number in JavaScript
How to Partition Input Field to Appear as Separate Input Fields on Screen
Jquery: Simplest Way to Check Url for a Parameter and Pass It to Anchor Href If It Exists
How to Pass 3 Parameters in Onclick Function .The Parameters Are Inside PHP Tag
Split a String Only the At the First N Occurrences of a Delimiter
How to Separate String and Push to React State
How to Protect HTML Form from Blank Submission
How to Open Specific Web Browsers Using Hyperlinks
Way to Access Const from Another Component in React
How to Import File from Public Folder in React Application
How to Convert File to Base64 in JavaScript
How to Convert Gmt Time to Ist Time in JavaScript
Image Taken from Camera Not Saved to Gallery
How to Change the Font Color, Font Size, and Button Color in React
How to Set a Header Field on Post a Form
How to Output Date in JavaScript in Iso 8601 Without Milliseconds and With Z
Json Object Array Inside Array Find and Replace in JavaScript