I have object with such fields:
{
d_name: { field_name: true },
d_date: { field_date: ISODate() },
status: 'success'
}
I need to get fields starting with d_ and then push them to one array..
I need to get fields...
Do you mean you need to get the keys? If so:
var d_keys = Object.keys(obj).filter(function (key) {
return !key.indexOf("d_");
});
If you actually want the values:
var d_values = Object.keys(obj).filter(function (key) {
return !key.indexOf("d_");
}).map(function (key) {
return obj[key];
});
Note that this uses various ES5 methods (Object.keys, Array.prototype.filter and Array.prototype.map), so depending on your environment you may need appropriate shims.
Here are working examples of both snippets.
You can iterate over the keys of the object, then compare the start of the key name:
var myObj = {
d_name: { field_name: true },
d_date: { field_date: ISODate() },
status: 'success'
};
var outArray = {};
for(var key in myObj) {
if(key.length >= 2 && key.substr(0,2) == "d_") {
outArray[key] = myObj[key];
}
}
Here is the fiddle hope it helps you
var q = [];
for(k in s)
{
if(k.indexOf("d_") == 0){
q.push(s[k]);
}
Related
I have an original object that is modified after an API call. I need to make sure that any fields that were originally not empty are reassigned to their original value. For example if articleTitle was initially filled out, and then after the API call it gets replaced with an empty value, I want to reassign it back to the original articleTitle value from the old object.
The two objects have the same keys, but I can't assume that the data coming back from the response is always going to be valid (but the original object always has valid data, that's why I need to reassign any empty fields to original values).
I (kinda) have a theoretically functional method, however I'm wondering if there is a more efficient way to do this. Here's what I have:
function evaluateEmptyValues = (originalReference, reference) {
// Get keys of both reference objects
var newReference = Object.entries(reference);
var oldReference = Object.entries(originalReference);
// Get length of both reference objects
var newReferenceLength = newReference.length;
var oldReferenceLength = oldReference.length;
// Double check objects are of the same length -- they always should be
if (newReferenceLength == oldReferenceLength) {
// Cycle through both objects
for (var i = 0; i < newReference.length; i++) {
console.log('i is ' + i);
// Again, these two lengths should be equal
if (newReference[i].length == oldReference[i].length) {
// Check if elements in current iteration is an object --
// if one is an object, then the other SHOULD also be
if ((typeof(newReference[i][j]) == 'object' &&
typeof(oldReference[i][j]) == 'object'
) {
// If both are objects, repeat lines 3 and 4
var currentNewReference = Object.entries(newReference[i][j]);
var currentOldReference = Object.entries(oldReference[i][j]);
// Get their lengths
var currentNewReferenceLength = currentNewReference.length;
var currentOldReferenceLength = currentOldReference.length;
// Both should be of the same length
if (currentNewReferenceLength == currentOldReferenceLength) {
for (var io = 0; io < currentNewReferenceLength.length; io++) {
console.log('io is ' + io);
// Both should also be of the same length
if (currentNewReference[io].length == currentOldReference[io].length) {
// For each iteration...
for (var jo = 0; jo < currentNewReference[io].length; jo++) {
// Check for empty values
if (currentNewReference[io][jo] == undefined ||
currentNewReference[io][jo] == null ||
(typeof(currentNewReference[io][jo]) == 'string' && currentNewReference[io][jo].trim() == '')
) {
// If empty, then reassign the empty value in the new reference
// object with the value of the field from the old reference
// object, regardless of whether or not the old value is also empty/null
currentNewReference[io][jo] = currentOldReference[io][jo];
}
}
} else {
// Serious problem
}
}
} else {
// Serious problem
}
} else {
// Cycle through current field
for (var j = 0; j < newReference[i].length; j++) {
// Check for nulls or empties
if (newReference[i][j] == undefined ||
newReference[i][j] == null ||
(typeof(newReference[i][j]) == 'string' && newReference[i][j].trim() == '')
) {
// Assign old value to new value, regardless of
// whether or not old value is also empty
newReference[i][j] = oldReference[i][j];
}
}
}
} else {
// Serious problem
}
}
} else {
// Serious problem
}
I doubt this is a very scalable or maintainable approach, and I'm wondering if there are any suggestions on enhancing this function, preferably using ES5, unless the ES6+ version works in most browsers.
For some reference, here are the two objects:
Here, articleTitle is empty.
Here, it is filled out from the API call. This is expected and needed, however imagine if it was the other way around, and articleTitle came back empty in the newReference after the API call
Edit:
Using the accepted answer plus an adjustment, this solved my specific problem:
function evaluateEmptyValues(reference, originalReference) {
var vm = this;
// Get keys and values of both reference objects
referenceLength = Object.entries(reference).length;
originalReferenceLength = Object.entries(originalReference).length;
if (referenceLength == originalReferenceLength) {
try {
// Cycle through both objects
for (var prop in reference) {
if (reference[prop] != undefined || reference[prop] != null) {
if (typeof (reference[prop]) == 'string' && reference[prop].trim() != '') {
// If both current elements are objects, recurse
if (typeof reference[prop] == 'object' && typeof originalReference[prop] == 'object') {
vm.evaluateEmptyValues(reference[prop], originalReference[prop])
}
// If both current elements are arrays, recurse
if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {
reference[prop].forEach((item, index) => vm.evaluateEmptyValues(item, originalReference[prop][index]));
}
// If new value is null, empty or undefined, assign it to old value,
// regardless of whether or not the old value was also null/empty.
//
///// This is to ensure that no existing previous values are
///// overwritten with any nulls or empty values
} else {
reference[prop] = originalReference[prop];
}
} else {
reference[prop] = originalReference[prop];
}
}
} catch(err) {
console.log(err);
}
}
console.log(reference);
You can simplify your function by a lot using recursion and a for ... in loop. I made two test objects to illustrate all the cases of your original example. In case it hits an array of objects it will iterate through that array and check for empty values recursively as well. Please see snippet below:
function evaluateEmptyValues(reference, originalReference) {
if (reference.length == originalReference.length) {
for (var prop in reference) {
if (typeof reference[prop] == 'object' && typeof originalReference[prop] == 'object') {
evaluateEmptyValues(reference[prop], originalReference[prop])
}
if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {
reference[prop].forEach((item, index) => evaluateEmptyValues(item, originalReference[prop][index]));
}
if (reference[prop] == undefined || reference[prop] == null ||
(typeof (reference[prop]) == 'string' && reference[prop].trim() == '')) {
reference[prop] = originalReference[prop];
}
}
}
}
const original = {
name: "Jack",
employee: {
firstName: "Nathan",
favoriteAnimal: {
species: "Donkey",
nature: "Lazy"
},
favoriteBeverages: [
{ name: "Beer", temperature: "Cold" },
{ name: "More beer", temperature: "Colder" }
]
},
occupation: "Plumber"
}
const newObject = {
name: "Jack",
employee: {
firstName: " ",
favoriteAnimal: {
species: null,
nature: "Lazy"
},
favoriteBeverages: [
{ name: "Beer", temperature: ""},
{ name: null, temperature: "Colder" }
]
},
occupation: undefined
}
evaluateEmptyValues(newObject, original);
console.log(newObject);
I think instead of using lot's of if conditions, you can try lodash, and use isEqual method which do a deep comparison between two values ( in your case two objects ), your code can be much cleaner as well.
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
You could make use of a recursive function. Something like this.
function mapper(oldObj, newObj) {
Object.entries(oldObj).forEach(([key, value]) => {
if (!newObj[key]) {
newObj[key] = value;
} else if (Array.isArray(newObj[key])) {
newObj[key].forEach((o, i) => mapper(oldObj[key][i], o));
} else if (Object.prototype.toString.call(newObj[key]) === "[object Object]") {
mapper(oldObj[key], newObj[key]);
}
});
return newObj;
}
const next = mapper(oldObj, newObj);
This will basically loop over all the items in the original object, and set the key/value in the new object if it doesn't exist.
So I've been trying to find a solution to this for a little while with no luck.
const nameTest = 'testName';
const test = {
RANDOM_ONE: {
NAME: 'testName',
SOMETHING: {...}
},
RANDOM_TWO: {
NAME: 'Name',
SOMETHING: {...}
}
}
Is there any simple, easy way where I can compare the nameTest and the NAME key without knowing what the RANDOM_X is in order to access NAME?
You can use Object.keys() to get the array of all the keys. Then loop through the array to check the property:
const nameTest = 'testName';
const test = {
RANDOM_ONE: {
NAME: 'testName',
SOMETHING: {}
},
RANDOM_TWO: {
NAME: 'Name',
SOMETHING: {}
}
}
let testKeys = Object.keys(test);
testKeys.forEach(function(k){
console.log(test[k].NAME == nameTest);
});
You can use a for ... in loop:
for (let key in test) {
if (test[key].NAME === nameTest) {
// do something
}
}
I hope we know that 2 levels down into test is your object. You could write a function, to compare the name key.
function compare(obj, text){
for(let x in obj){
if(obj.x.name == text) return true;
else ;
}
}
Then call the function with your object and the string.
let a = compare(test, nameTest);
Note: this would compare the object to only ascertain if it contains the nameTest string.
var obj= test.filter(el){
if(el.NAME==nameTest)
{
return el;
}
}
var x= obj!=null?true:false;
You could use find.
The find method executes the callback function once for each index of
the array until it finds one where callback returns a true value. If
such an element is found, find immediately returns the value of that
element. Otherwise, find returns undefined.
So it is more memory efficient, than looping over the whole object with forEach, because find returns immediately if the callback function finds the value. Breaking the loop of forEach is impossible. In the documentation:
There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behavior, the forEach() method
is the wrong tool.
1. If you want to get the whole object
var nameTest = 'testName';
var test = {
RANDOM_ONE: {
NAME: 'testName',
SOMETHING: {}
},
RANDOM_TWO: {
NAME: 'Name',
SOMETHING: {}
}
};
function getObjectByNameProperty(object, property) {
var objectKey = Object.keys(object)
.find(key => object[key].NAME === property);
return object[objectKey];
}
var object = getObjectByNameProperty(test, nameTest);
console.log(object);
2. If you just want to test if the object has the given name value
var nameTest = 'testName';
var test = {
RANDOM_ONE: {
NAME: 'testName',
SOMETHING: {}
},
RANDOM_TWO: {
NAME: 'Name',
SOMETHING: {}
}
};
function doesObjectHaveGivenName(object, nameValue) {
var objectKey = Object.keys(object)
.find(key => object[key].NAME === nameValue);
return objectKey ? true : false;
}
console.log( doesObjectHaveGivenName(test, nameTest) );
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 years ago.
Here I have an issue(sample code below). How to get rid of undefined?
In my case I can use only one variable like
object[dynamicKey]
but if the key is deeper in object then first level I get errors.
object = {
name: 'peter',
kidsNames: {
name: 'carlos',
}
}
dynamicKey1 = 'name';
dynamicKey2 = 'kidsNames.name';
console.log(object[dynamicKey1]); // 'peter'
console.log(object[dynamicKey2]); // undefined ???
I want a solution in pure JavaScript
SOLUTION:
Thanks for the help!
With your help guys I came up with solution like:
const getProp = (obj, prop) => {
return prop.split('.').reduce((r, e) => {
return r[e];
}, obj);
};
getProp(object, dynamicKey2) // 'carlos'
So now you it doesent matter how deep into object you need to go it always gives you the right value.
Use can use recursive call to solve this. see code below:
var object = {
name: 'peter',
kidsNames: {
name: 'carlos',
}
}
dynamicKey1 = 'name';
dynamicKey2 = 'kidsNames.name';
object[dynamicKey1]; // 'peter'
object[dynamicKey2];
function getValue(data, keys) {
// If plain string, split it to array
if(typeof keys === 'string') {
keys = keys.split('.')
}
// Get key
var key = keys.shift();
// Get data for that key
var keyData = data[key]
// Check if there is data
if(!keyData) {
return undefined;
}
// Check if we reached the end of query string
if(keys.length === 0){
return keyData;
}
// recusrive call!
return getValue(Object.assign({}, keyData), keys);
}
console.log(getValue(object, dynamicKey1))
console.log(getValue(object, dynamicKey2))
It doesn't work because JS thinks that kidsNames.name itself as a key name and tries to do
object['kidsNames.name']
Which don't work. But you can start with a basic idea
var keyNames = dynamicKey2.split(".");
object[keyNames[0]][keyNames[1]];
If you have n levels try using a loop.
var myobject = {
name: 'peter',
kidsNames: {
name: 'carlos',
}
}
dynamicKey1 = 'name';
dynamicKey2 = 'kidsNames.name';
var keyNames = dynamicKey2.split(".");
console.log(myobject[dynamicKey1]); // 'peter'
console.log(myobject[keyNames[0]][keyNames[1]]); //carlos
object = {
name: 'peter',
kidsNames: {
name: 'carlos',
child: {
name: 'myChild',
child: {
fullname: 'Sam williams'
}
}
}
}
dynamicKey1 = 'name';
dynamicKey2 = 'kidsNames.name';
dynamicKey3 = 'kidsNames.child.name';
dynamicKey4 = 'kidsNames.child.child.fullname';
console.log(reduce(object, dynamicKey1));
console.log(reduce(object, dynamicKey2));
console.log(reduce(object, dynamicKey3));
console.log(reduce(object, dynamicKey4));
function reduce(obj, key) {
var keySplit = key.split('.');
if (keySplit.length > 1) {
return reduce(obj[keySplit[0]], keySplit.slice(1, keySplit.length).join("."));
}
if (keySplit.length == 1) {
return obj[key];
} else {
return obj;
}
}
This will work for any number of child elements, if they are object, but not array or list. (recursive method)
Let's say we have this JavaScript object:
var object = {
innerObject:{
deepObject:{
value:'Here am I'
}
}
};
How can we check if value property exists?
I can see only two ways:
First one:
if(object && object.innerObject && object.innerObject.deepObject && object.innerObject.deepObject.value) {
console.log('We found it!');
}
Second one:
if(object.hasOwnProperty('innerObject') && object.innerObject.hasOwnProperty('deepObject') && object.innerObject.deepObject.hasOwnProperty('value')) {
console.log('We found it too!');
}
But is there a way to do a deep check? Let's say, something like:
object['innerObject.deepObject.value']
or
object.hasOwnProperty('innerObject.deepObject.value')
There isn't a built-in way for this kind of check, but you can implement it easily. Create a function, pass a string representing the property path, split the path by ., and iterate over this path:
Object.prototype.hasOwnNestedProperty = function(propertyPath) {
if (!propertyPath)
return false;
var properties = propertyPath.split('.');
var obj = this;
for (var i = 0; i < properties.length; i++) {
var prop = properties[i];
if (!obj || !obj.hasOwnProperty(prop)) {
return false;
} else {
obj = obj[prop];
}
}
return true;
};
// Usage:
var obj = {
innerObject: {
deepObject: {
value: 'Here am I'
}
}
}
console.log(obj.hasOwnNestedProperty('innerObject.deepObject.value'));
You could make a recursive method to do this.
The method would iterate (recursively) on all 'object' properties of the object you pass in and return true as soon as it finds one that contains the property you pass in. If no object contains such property, it returns false.
var obj = {
innerObject: {
deepObject: {
value: 'Here am I'
}
}
};
function hasOwnDeepProperty(obj, prop) {
if (typeof obj === 'object' && obj !== null) { // only performs property checks on objects (taking care of the corner case for null as well)
if (obj.hasOwnProperty(prop)) { // if this object already contains the property, we are done
return true;
}
for (var p in obj) { // otherwise iterate on all the properties of this object.
if (obj.hasOwnProperty(p) && // and as soon as you find the property you are looking for, return true
hasOwnDeepProperty(obj[p], prop)) {
return true;
}
}
}
return false;
}
console.log(hasOwnDeepProperty(obj, 'value')); // true
console.log(hasOwnDeepProperty(obj, 'another')); // false
Alternative recursive function:
Loops over all object keys. For any key it checks if it is an object, and if so, calls itself recursively.
Otherwise, it returns an array with true, false, false for any key with the name propName.
The .reduce then rolls up the array through an or statement.
function deepCheck(obj,propName) {
if obj.hasOwnProperty(propName) { // Performance improvement (thanks to #nem's solution)
return true;
}
return Object.keys(obj) // Turns keys of object into array of strings
.map(prop => { // Loop over the array
if (typeof obj[prop] == 'object') { // If property is object,
return deepCheck(obj[prop],propName); // call recursively
} else {
return (prop == propName); // Return true or false
}
}) // The result is an array like [false, false, true, false]
.reduce(function(previousValue, currentValue, index, array) {
return previousValue || currentValue;
} // Do an 'or', or comparison of everything in the array.
// It returns true if at least one value is true.
)
}
deepCheck(object,'value'); // === true
PS: nem035's answer showed how it could be more performant: his solution breaks off at the first found 'value.'
My approach would be using try/catch blocks. Because I don't like to pass deep property paths in strings. I'm a lazy guy who likes autocompletion :)
JavaScript objects are evaluated on runtime. So if you return your object statement in a callback function, that statement is not going to be evaluated until callback function is invoked.
So this function just wraps the callback function inside a try catch statement. If it catches the exception returns false.
var obj = {
innerObject: {
deepObject: {
value: 'Here am I'
}
}
};
const validate = (cb) => {
try {
return cb();
} catch (e) {
return false;
}
}
if (validate(() => obj.innerObject.deepObject.value)) {
// Is going to work
}
if (validate(() => obj.x.y.z)) {
// Is not going to work
}
When it comes to performance, it's hard to say which approach is better.
On my tests if the object properties exist and the statement is successful I noticed using try/catch can be 2x 3x times faster than splitting string to keys and checking if keys exist in the object.
But if the property doesn't exist at some point, prototype approach returns the result almost 7x times faster.
See the test yourself: https://jsfiddle.net/yatki/382qoy13/2/
You can also check the library I wrote here: https://github.com/yatki/try-to-validate
I use try-catch:
var object = {
innerObject:{
deepObject:{
value:'Here am I'
}
}
};
var object2 = {
a: 10
}
let exist = false, exist2 = false;
try {
exist = !!object.innerObject.deepObject.value
exist2 = !!object2.innerObject.deepObject.value
}
catch(e) {
}
console.log(exist);
console.log(exist2);
Try this nice and easy solution:
public hasOwnDeepProperty(obj, path)
{
for (var i = 0, path = path.split('.'), len = path.length; i < len; i++)
{
obj = obj[path[i]];
if (!obj) return false;
};
return true;
}
In case you are writing JavaScript for Node.js, then there is an assert module with a 'deepEqual' method:
const assert = require('assert');
assert.deepEqual(testedObject, {
innerObject:{
deepObject:{
value:'Here am I'
}
}
});
I have created a very simple function for this using the recursive and happy flow coding strategy. It is also nice to add it to the Object.prototype (with enumerate:false!!) in order to have it available for all objects.
function objectHasOwnNestedProperty(obj, keys)
{
if (!obj || typeof obj !== 'object')
{
return false;
}
if(typeof keys === 'string')
{
keys = keys.split('.');
}
if(!Array.isArray(keys))
{
return false;
}
if(keys.length == 0)
{
return Object.keys(obj).length > 0;
}
var first_key = keys.shift();
if(!obj.hasOwnProperty(first_key))
{
return false;
}
if(keys.length == 0)
{
return true;
}
return objectHasOwnNestedProperty(obj[first_key],keys);
}
Object.defineProperty(Object.prototype, 'hasOwnNestedProperty',
{
value: function () { return objectHasOwnNestedProperty(this, ...arguments); },
enumerable: false
});
I'm having a really hard time trying to find a way to iterate through this object in the way that I'd like. I'm using only Javascript here.
First, here's the object
{
"dialog":
{
"dialog_trunk_1":{
"message": "This is just a JSON Test"
},
"dialog_trunk_2":{
"message": "and a test of the second message"
},
"dialog_trunk_3":
{
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
}
}
Right now, I'm just trying basic ways to get through to each dialog_trunk on this object. I ideally want to loop through the object and for each trunk, display it's message value.
I've tried using a for loop to generate the name/number of the dialog_trunk on the fly, but I can't access the object using a string for the object name so I'm not sure where to go from here.
You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.
{
"dialog":
{
"trunks":[
{
"trunk_id" : "1",
"message": "This is just a JSON Test"
},
{
"trunk_id" : "2",
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
]
}
}
At that point, I was able to do a fairly simple for loop based on the total number of objects.
var totalMessages = Object.keys(messages.dialog.trunks).length;
for ( var i = 0; i < totalMessages; i++)
{
console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
}
My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.
Here is my recursive approach:
function visit(object) {
if (isIterable(object)) {
forEachIn(object, function (accessor, child) {
visit(child);
});
}
else {
var value = object;
console.log(value);
}
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
An improved version for recursive approach suggested by #schirrmacher to print key[value] for the entire object:
var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
jDepthLvl++;
if (isIterable(object)) {
if(objectAccessor === null) {
console.log("%c ⇓ ⇓ printing object $OBJECT_OR_ARRAY$ -- START ⇓ ⇓", "background:yellow");
} else
console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
forEachIn(object, function (accessor, child) {
visit(child, accessor);
});
} else {
var value = object;
console.log("%c"
+ spacesDepth(jDepthLvl)
+ objectAccessor + "[%c" + value + "%c] "
,"color:blue","color:red","color:blue");
}
if(objectAccessor === null) {
console.log("%c ⇑ ⇑ printing object $OBJECT_OR_ARRAY$ -- END ⇑ ⇑", "background:yellow");
}
jDepthLvl--;
}
function spacesDepth(jDepthLvl) {
let jSpc="";
for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
jSpc+="\u0020\u0020"
}
return jSpc;
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
visit($OBJECT_OR_ARRAY$);
var res = {
"dialog":
{
"dialog_trunk_1":{
"message": "This is just a JSON Test"
},
"dialog_trunk_2":{
"message": "and a test of the second message"
},
"dialog_trunk_3":
{
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
}
}
for (var key in res) {
if (res.hasOwnProperty(key)) {
var val = res[key];
for (var key in val) {
if (val.hasOwnProperty(key)) {
var dialog = val[key];
console.log(dialog.message);
}
}
}
}
The simpler approach is (just found on W3Schools):
let data = {.....}; // JSON Object
for(let d in data){
console.log(d); // It gives you property name
console.log(data[d]); // And this gives you its value
}
UPDATE
This approach works fine until you deal with the nested object so this approach will work.
const iterateJSON = (jsonObject, output = {}) => {
for (let d in jsonObject) {
if (typeof jsonObject[d] === "string") {
output[d] = jsonObject[d];
}
if (typeof jsonObject[d] === "object") {
output[d] = iterateJSON(jsonObject[d]);
}
}
return output;
}
And use the method like this
let output = iterateJSON(your_json_object);