I have a javascript object like this
const allData = {
"aaa": {
"xxx": {},
"details": {
"111": {
"a": 1
}
}
},
"bbb": {
"yyy": {},
"details": {
"222": {
"a": 10
}
}
},
"ccc": {
"zzz": {},
"details": {
"333": {
"a": 100
}
}
},
"ddd": {
"kkk": {},
"details": {
"444": {
"a": 1000
}
}
}
};
and I like to get all details to another one, so:
allDetails={};
$.each(allData, function (nameCont, valCont){
console.dir(valCont.details);
Object.defineProperty(allDetails, nameCont, valCont.details);
});
console.dir(allDetails);
I expect the result should be:
{
"aaa": {
"111": {
"a": 1
}
},
"bbb": {
"222": {
"a": 10
}
},
"ccc": {
"333": {
"a": 100
}
},
"ddd": {
"444": {
"a": 1000
}
}
}
But it doesn’t work… What’s wrong?
Here the fiddle
4
Answers
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Your call to this:
passes a value as the
descriptor
, not a descriptor, so should be:Updated fiddle: https://jsfiddle.net/th1ves6q/
use …spread syntax
Nested
for of
usingObject.entries
on first loop get the first key and record its value to results creating an empty object, then on second loop get thevalue.details
key/value and record that to results.