If I have this JSON data that is from the original file.
[{"food": {"spicy": "spicy","sweet": "sweet"},
"water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}, {"food": {"spicy": "spicy","sweet": "sweet"},
"water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}]
how do I convert into a one-dimensional list like this?
[{
"food-spicy": "spicy",
"food-sweet ": "sweet",
"water-sweet ": "sweet",
"water-sour-cold ": "ice lemon",
"water-sour-hot ": "lemon tea"
}, {
"food-spicy": "spicy",
"food-sweet ": "sweet",
"water-sweet ": "sweet",
"water-sour-cold ": "ice lemon",
"water-sour-hot ": "lemon tea"
}]
Please help.
You could write a function that flatten an object recursively. Then map the array using that function:
function flatten(oldObj) {
return Object.keys(oldObj).reduce(function(newObj, oldKey) { // for each key "oldKey" in oldObj
var value = oldObj[oldKey]; // get the value of the current oldKey from oldObj
if(value && typeof(value) === "object") { // if the value is also an object (add "&& !Array.isArray(value)" to exclude arrays)
value = flatten(value); // then flatten it first
Object.keys(value).forEach(function(key) { // and for each key in the new flattened value object
newObj[oldKey + "-" + key] = value[key]; // add a key-value to newObj where key is "oldKey-key" and the value is value[key]
});
} else {
newObj[oldKey] = value; // otherwise (if the value is not an object), just copy the key-value to newObj as it is
}
return newObj;
}, {});
}
Then use it like this:
var newArray = oldArray.map(flatten);
Example:
function flatten(oldObj) {
return Object.keys(oldObj).reduce(function(newObj, oldKey) {
var value = oldObj[oldKey];
if(value && typeof(value) === "object") {
value = flatten(value);
Object.keys(value).forEach(function(key) {
newObj[oldKey + "-" + key] = value[key];
});
} else {
newObj[oldKey] = value;
}
return newObj;
}, {});
}
var oldArray = [{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}},{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}}];
var newArray = oldArray.map(flatten);
console.log(newArray);
try this:
var data = [{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
},
{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
}
]
var res = data.map(obj => {
return Reflect.ownKeys(obj).reduce((re, key) => {
Reflect.ownKeys(obj[key]).reduce((r, k) => {
if (typeof obj[key][k] === 'object') {
Reflect.ownKeys(obj[key][k]).reduce((r2, k2) => {
r2[key + '-' + k + '-' + k2] = obj[key][k][k2]
return r2
}, r)
} else {
r[key + '-' + k] = obj[key][k]
return r
}
}, re)
return re
}, {})
})
console.log(res)
And here is a more universal version which applicable for more nested obj
var data = [{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
},
{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
}
]
function customReduce(obj, subObj, lastReduceObj = {}, lastKey = '') {
let res = Reflect.ownKeys(subObj).reduce((re, key) => {
if (lastKey === '') {
customReduce(obj, obj[key], re, key)
} else if (typeof subObj[key] === 'object') {
customReduce(obj, subObj[key], re, lastKey + '-' + key)
} else {
re[lastKey + '-' + key] = subObj[key]
}
return re
}, lastReduceObj)
return res
}
var res = data.map(obj => {
return customReduce(obj, obj)
})
console.log(res)
Try this :
var jsonObj = [{
"food": {
"spicy": "spicy",
"sweet": "sweet"
},
"water": {
"sweet": "sweet",
"sour": {
"cold": "ice lemon",
"hot": "lemon tea"
}
}
}, {
"food": {
"spicy": "spicy",
"sweet": "sweet"
},
"water": {
"sweet": "sweet",
"sour": {
"cold": "ice lemon",
"hot": "lemon tea"
}
}
}];
var newObj = {};
for (var i in jsonObj) {
for (var j in Object.keys(jsonObj[i])) {
for (var k in Object.keys(jsonObj[i])[j]) {
newObj[Object.keys(jsonObj[i])[j]+'-'+Object.keys(jsonObj[i][Object.keys(jsonObj[i])[j]])[k]] = jsonObj[i][Object.keys(jsonObj[i])[j]][Object.keys(jsonObj[i][Object.keys(jsonObj[i])[j]])[k]];
}
}
}
console.log([flatJSON(newObj)]);
function flatJSON(obj) {
if(typeof obj != 'object') {
return;
}
for (var l in Object.keys(obj)) {
if (typeof obj[Object.keys(obj)[l]] == 'object') {
for (var m in Object.keys(obj[Object.keys(obj)[l]])) {
newObj[Object.keys(obj)[l]+'-'+Object.keys(obj[Object.keys(obj)[l]])[m]] = obj[Object.keys(obj)[l]][Object.keys(obj[Object.keys(obj)[l]])[m]];
}
}
if (typeof obj[Object.keys(obj)[l]] == 'object') {
delete obj[Object.keys(obj)[l]];
}
if (obj[Object.keys(obj)[l]] === undefined) {
delete obj[Object.keys(obj)[l]];
}
}
return newObj;
}
Related
I need to convert object:
{
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
}
to array:
[{
key: "name",
propertyValue: "Test Name",
},
{
key: "middleName",
propertyValue: null,
},
{
key: "university.isGraduated",
propertyValue: true,
},
{
key: "university.speciality",
propertyValue: "Computer Science",
},
{
key: "university.country.code",
propertyValue: "PL"
}];
I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")
let arr = [];
Object.keys(parsedObj).map((key) => {
if (parsedObj[key] instanceof Object) {
Object.keys(parsedObj[key]).map((keyNested) => {
if (parsedObj[key][keyNested] instanceof Object) {
Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
})
} else {
arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
}
})
} else {
arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
}
});
Thanks
A recursive function implementation.
I have considered that your object consist of only string and object as the values. If you have more kind of data types as your values, you may have to develop on top of this function.
const myObj = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
}
const myArr = [];
function convertObjectToArray(obj, keyPrepender) {
Object.entries(obj).forEach(([key, propertyValue]) => {
if (typeof propertyValue === "object" && propertyValue) {
const updatedKey = keyPrepender ? `${keyPrepender}.${key}` : key;
convertObjectToArray(propertyValue, updatedKey)
} else {
myArr.push({
key: keyPrepender ? `${keyPrepender}.${key}` : key,
propertyValue
})
}
})
}
convertObjectToArray(myObj);
console.log(myArr);
I'd probably take a recursive approach, and I'd probably avoid unnecessary intermediary arrays (though unless the original object is massive, it doesn't matter). For instance (see comments):
function convert(obj, target = [], prefix = "") {
// Loop through the object keys
for (const key in obj) {
// Only handle "own" properties
if (Object.hasOwn(obj, key)) {
const value = obj[key];
// Get the full key for this property, including prefix
const fullKey = prefix ? prefix + "." + key : key;
if (value && typeof value === "object") {
// It's an object...
if (Array.isArray(value)) {
throw new Error(`Arrays are not valid`);
} else {
// ...recurse, providing the key as the prefix
convert(value, target, fullKey);
}
} else {
// Not an object, push it to the array
target.push({key: fullKey, propertyValue: value});
}
}
}
// Return the result
return target;
}
Live Example:
const original = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
};
function convert(obj, target = [], prefix = "") {
// Loop through the object keys
for (const key in obj) {
// Only handle "own" properties
if (Object.hasOwn(obj, key)) {
const value = obj[key];
// Get the full key for this property, including prefix
const fullKey = prefix ? prefix + "." + key : key;
if (value && typeof value === "object") {
// It's an object...
if (Array.isArray(value)) {
throw new Error(`Arrays are not valid`);
} else {
// ...recurse, providing the key as the prefix
convert(value, target, fullKey);
}
} else {
// Not an object, push it to the array
target.push({key: fullKey, propertyValue: value});
}
}
}
// Return the result
return target;
}
const result = convert(original, []);
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
}
Note that I've assumed the order of the array entries isn't significant. The output you said you wanted is at odds with the standard order of JavaScript object properties (yes, they have an order now; no, it's not something I suggest relying on 😀). I've gone ahead and not worried about the order within an object.
This is the most bulletproof I could do :D, without needing a global variable, you just take it, and us it wherever you want!
const test = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
};
function toPropertiesByPath(inputObj) {
let arr = [];
let initialObj = {};
const getKeys = (obj, parentK='') => {
initialObj = arr.length === 0 ? obj: initialObj;
const entries = Object.entries(obj);
for(let i=0; i<entries.length; i++) {
const key = entries[i][0];
const val = entries[i][1];
const isRootElement = initialObj.hasOwnProperty(key);
parentK = isRootElement ? key: parentK+'.'+key;
if(typeof val === 'object' && val!==null && !Array.isArray(val)){
getKeys(val, parentK);
} else {
arr.push({ key: parentK, property: val });
}
}
};
getKeys(inputObj);
return arr;
}
console.log(toPropertiesByPath(test));
I wrote a small version using recursive function and another for validation is an object.
let values = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
}
function isObject(obj) {
return obj != null && obj.constructor.name === "Object"
}
function getValues(values) {
let arrValues = Object.keys(values).map(
v => {
return { key: v, value: isObject(values[v]) ? getValues(values[v]) : values[v] };
});
console.log(arrValues);
}
getValues(values);
Given the following object:
const ourObject = {
"payload": {
"streams": [
{
"children": {
"2165d20a-6276-468f-a02f-1abd65cad618": {
"additionalInformation": {
"narrative": {
"apple": "A",
"banana": "B"
},
"myInventory": {
"fruits": [
{
"name": "apple"
},
{
"name": "banana"
}
]
}
}
}
}
}
]
}
};
We're trying to find the path of myInventory, the issue is that the children's uuid will be different each time. Any idea how we can get the path to myInventory by providing it as a key and get the json path to it?
If things are dynamic, a programmatic key search could help
const ourObject = {
"payload": {
"streams": [
{
"children": {
"2165d20a-6276-468f-a02f-1abd65cad618": {
"additionalInformation": {
"narrative": {
"apple": "A",
"banana": "B"
},
"myInventory": {
"fruits": [
{
"name": "apple"
},
{
"name": "banana"
}
]
}
}
}
}
}
]
}
};
const getPath = (key, o) => {
if (!o || typeof o !== "object") {
return "";
}
const keys = Object.keys(o);
for(let i = 0; i < keys.length; i++) {
if (keys[i] === key ) {
return key;
}
const path = getPath(key, o[keys[i]]);
if (path) {
return keys[i] + "." + path;
}
}
return "";
};
const getValueForKey = (key, o) => {
if (!o || typeof o !== "object") {
return undefined;
}
const keys = Object.keys(o);
for(let i = 0; i < keys.length; i++) {
if (keys[i] === key ) {
return o[key];
}
const value = getValueForKey(key, o[keys[i]]);
if (value) {
return value;
}
}
return undefined;
}
console.log(getPath("myInventory", ourObject))
console.log(getValueForKey("myInventory", ourObject))
Not sure if I understand the question right but
let uuid = '2165d20a-6276-468f-a02f-1abd65cad618';
ourObject.payload.streams[0].children[uuid].additionalInformation.myInventory
var changingKey = Object.keys(ourObject["payload"]["streams"][0]["children"])[0];
console.log(ourObject["payload"]["streams"][0]["children"][changingKey]["additionalInformation"]["myInventory"]);
Okay, you could create a helper function that gets the UUID. Since it's an object, the lookup is close to O(1) especially given the case that the children has only one key-value pair here.
function getUUIDFromPayload(payload) {
let obj = payload.streams[0].children
let uuid = Object.keys(obj)[0]
return uuid
}
Usage
const uuid = getUUIDFromPayload(payload)
ourObject.payload.streams[0].children[uuid].additionalInformation.myInventory
JSON: (I have two same object properties in array. i would like merge all the property values of this array. I have added other case, if id gets changed, it should give like below. )
const array = [{
Lot_id:{
id:1,
qty_receive:30,
qty_return:5,
qty_remain:15
},
qty_allocate:10,
remaining_qty:20
},
{
Lot_id:{
id:1,
qty_receive:30,
qty_return:5,
qty_remain:15
},
qty_allocate:10,
remaining_qty:20
},
{
Lot_id:{
id:2,
qty_receive:30,
qty_return:5,
qty_remain:15
},
qty_allocate:10,
remaining_qty:20
}]
expected result:(updated my question)
const array = [{
Lot_id:{
id:1,
qty_receive:60,
qty_return:10,
qty_remain:30
}
qty_allocate:20,
remaining_qty:40
},
{
Lot_id:{
id:2,
qty_receive:30,
qty_return:5,
qty_remain:15
},
qty_allocate:10,
remaining_qty:20
}]
Can u try this?
const array = [
{ Lot_id:{ id:1, qty_receive:30, qty_return:5, qty_remain:15}, qty_allocate:10},
{ Lot_id:{ id:1, qty_receive:30, qty_return:5, qty_remain:15}, qty_allocate:10},
{ Lot_id:{ id:2, qty_receive:30, qty_return:5, qty_remain:15}, qty_allocate:10},
]
function merge(array){
var result = [];
array.reduce(function(res, value) {
if (!res[value.Lot_id.id]) {
res[value.Lot_id.id] = {
Lot_id: {
id:value.Lot_id.id,
qty_receive:0,
qty_return:0,
qty_remain:0,
}, qty_allocate: 0
};
result.push(res[value.Lot_id.id])
}
res[value.Lot_id.id].qty_allocate += value.qty_allocate;
res[value.Lot_id.id].Lot_id.qty_receive += value.Lot_id.qty_receive;
res[value.Lot_id.id].Lot_id.qty_return += value.Lot_id.qty_return;
res[value.Lot_id.id].Lot_id.qty_remain += value.Lot_id.qty_remain;
return res;
}, {});
return result
}
console.log(merge(array));
const reduceArr = array.reduce((total, {Lot_id: {qty_receive, qty_return, qty_remain}, qty_allocate}) => {
total.Lot_id.qty_receive += qty_receive;
total.Lot_id.qty_return += qty_return;
total.Lot_id.qty_remain += qty_remain;
total.qty_allocate += qty_allocate;
return [total];
});
Update answer according to your updated question:
const mergeArr = () => {
const newArr = [];
let tempId = 0;
array.forEach((item, index) => {
if (tempId !== item.Lot_id.id) {
tempId = item.Lot_id.id;
newArr.push(item);
} else {
const lastItem = newArr[newArr.length - 1];
const lastLot = lastItem.Lot_id;
const newLot = item.Lot_id;
lastLot.qty_receive += newLot.qty_receive;
lastLot.qty_return += newLot.qty_return;
lastLot.qty_remain += newLot.qty_remain;
lastItem.remaining_qty += item.remaining_qty;
lastItem.qty_allocate += item.qty_allocate;
}
});
return newArr;
}
console.log(mergeArr());
try the code here:
https://repl.it/repls/SparseUnfortunateLanguage
Try this instead,
let result = mergeElements(array);
console.log(result);
/**
* function accepts the array of objects you need to merge by adding fields
* */
function mergeElements(array = []) {
let sumOf = [];
if (array.length <= 1) {
return array;
} else {
sumOf[0] = array[0];
let index = 0;
array.forEach(function (item, index) {
if (index != 0) {
sumOf[0] = iterateItem(item, sumOf[0]);
}
index++;
});
}
return sumOf;
}
/**
*function for indepth iteration of objects
* */
function iterateItem(item, sumOf) {
if (typeof item == "object") {
for (let key in item) {
if (typeof item[key] != "object") {
if (typeof sumOf[key] == "undefined") {
sumOf[key] = 0;
}
if (key == "id") {
continue;
}
sumOf[key] += item[key];
} else {
if (typeof sumOf[key] == "undefined") {
sumOf[key] = {};
}
sumOf[key] = iterateItem(item[key], sumOf[key]);
}
}
} else {
sumOf += item;
}
return sumOf;
}
I hope this will help you to solve your problem.
You can check my solution for your issue.
const array = [
{
Lot_id: {
id: 1,
qty_receive: 30,
qty_return: 5,
qty_remain: 15,
},
qty_allocate: 10,
},
{
Lot_id: {
id: 1,
qty_receive: 30,
qty_return: 5,
qty_remain: 15,
},
qty_allocate: 10,
},
{
another_id: {
id: 1,
qty_receive: 30,
qty_return: 5,
qty_remain: 15,
},
qty_allocate: 10,
},
{
another_id: {
id: 1,
qty_receive: 30,
qty_return: 5,
qty_remain: 15,
},
qty_allocate: 10,
},
];
const isObject = (value) => {
return (
typeof value === "object" &&
value instanceof Object &&
!(value instanceof Array)
);
};
const result = array.reduce((acc, obj) => {
const existingObj = acc.find((accObj) => {
return Object.keys(accObj).every(
(key) => Object.keys(obj).indexOf(key) > -1
);
});
if (existingObj) {
Object.keys(obj).forEach((key) => {
if (isObject(obj[key])) {
const innerObj = obj[key];
const existingInnerObj = existingObj[key];
Object.keys(innerObj).forEach((innerKey) => {
if(innerKey !== 'id') {
existingInnerObj[innerKey] += innerObj[innerKey];
}
});
} else {
existingObj[key] += obj[key];
}
});
} else {
acc.push(obj);
}
return acc;
}, []);
console.log(result);
I am converting JSON keys to the list with dot-notation. If any dot is there represent nested jsonobject and if any [](array notation) is there resents jsonarray.
var keyify = (obj, prefix = '') =>
Object.keys(obj).reduce((res, el) => {
if (Array.isArray(obj[el])) {
return [...res, ...keyify(obj[el][0], prefix + el + '[].')];
} else if (typeof obj[el] === 'object' && obj[el] !== null) {
return [...res, ...keyify(obj[el], prefix + el + '.')];
} else {
return [...res, prefix + el];
}
}, []);
Above is the sample code that I am using for the converion. If input is
{
"input": {
"test": {
"phone": [
{
"phone1": "123"
}
]
}
},
"customer": [
{
"lastname": "def",
"firstname": "abc"
}
]
}
Output will be:
[ 'input.test.phone[].phone1',
'customer[].lastname',
'customer[].firstname' ]
But the above code searches for only first JSONObject's keys in the JSONArray. But if the input is like this:
{
"input": {
"test": {
"phone": [
{
"phone1": "123"
},
{
"a": "456"
}
]
}
},
"customer": [
{
"lastname": "def",
"firstname": "abc"
}
]
}
Then in the above JSON case the code will give output :
[ 'input.test.phone[].phone1',
'customer[].lastname',
'customer[].firstname' ]
So, the key a is missing only phone1 is coming in the list.So, how to get if multiple json keys are there then get keys with index of first occurence.
Expected output
[ 'input.test.phone[0].phone1',
'input.test.phone[1].a',
'customer[0].lastname',
'customer[0].firstname' ]
And if the JSONarray is value then it should be replaced by empty string.
For input:
const data = {
"input": {
"test": {
"phone": [
{
"phone1": ["123456"]
},
{
"a": ["1","2","3","4"]
}
]
}
},
"customer": [
{
"lastname": "def",
"firstname": "abc"
}
]
}
In this case "phone1": ["123456"] and "a": ["1","2","3","4"] are Json array as values this case lis will be like:
Expected Output:
[ 'input.test.phone[0].phone1',//instead of 'input.test.phone[0].phone1[0]'
'input.test.phone[1].a',//instead of 'input.test.phone[1].a[0]','input.test.phone[1].a[1]','input.test.phone[1].a[2]','input.test.phone[1].a[3]',
'customer[0].lastname',
'customer[0].firstname' ]
In the above case jsonarray should be considered as value not key.
You could use for...in loop to create recursive function for this and check if the current data input is an array or not to add dot or square brackets.
const data = { "input": { "test": { "phone": [ { "phone1": ["123456"] }, { "a": ["1","2","3","4"] } ] } }, "customer": [ { "lastname": "def", "firstname": "abc" } ] }
function parse(data, prev = '') {
const result = []
const check = data => {
if (typeof data !== 'object') {
return false
}
if (Array.isArray(data)) {
if (data.some(e => (typeof e != 'object'))) {
return false
}
}
return true;
}
for (let i in data) {
let dot = prev ? '.' : ''
let str = Array.isArray(data) ? `[${i}]` : dot + i
let key = prev + str;
if (check(data[i])) {
result.push(...parse(data[i], key))
} else {
result.push(key)
}
}
return result
}
const result = parse(data);
console.log(result)
You can traverse through the scope of the object and capture any paths that have a non-object value.
This is an extremely uncoupled and generic soulution.
const traverse = (obj, visitorFn, scope = []) => {
for (let key in obj) {
visitorFn.apply(this, [key, obj[key], scope]);
if (obj[key] !== null && typeof obj[key] === 'object') {
traverse(obj[key], visitorFn, scope.concat(key));
}
}
}
const scopeToPath = (obj) => obj.reduce((path, key) =>
path + (!isNaN(key) ? `[${key}]` : `.${key}`), '').substring(1);
const findObjectPaths = (obj) => {
let paths = [];
traverse(obj, (key, value, scope) => {
if (typeof value !== 'object') {
paths.push(scopeToPath(scope.concat(key)));
}
});
return paths;
};
console.log(findObjectPaths(getData()));
function getData() {
return {
"input": {
"test": {
"phone": [{ "phone1": "123" }, { "a": "456" }]
}
},
"customer": [{ "lastname": "def", "firstname": "abc" }]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
You could take a nested approach by having a look to the types of the object.
function flat(object, keys = '') {
if (!object || typeof object !== 'object') return [keys];
if (Array.isArray(object))
return object.every(o => !o|| typeof o!== 'object')
? [keys]
: object.flatMap((o, i, { length }) =>
flat(o, `${keys}[${length === 1 ? '' : i}]`));
return Object
.entries(object)
.flatMap(([k, v]) => flat(v, `${keys}${keys && '.'}${k}`));
}
var data = { input: { test: { phone: [{ phone1: ["123456"] }, { a: ["1", "2", "3", "4"] }] } }, customer: [{ lastname: "def", firstname: "abc" }] },
result = flat(data);
console.log(result);
I have an Object:
{
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
}
I want to convert it to:
{
"Results": {
"circle": {
"circle": 0.06879016757011414
},
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": {
"square": 0.8266428709030151
}
}
}
Have tried this code:
var modData = {};
data = data.Results;
for (var key in data) {
if (data.hasOwnProperty(key)) {
modData[key] = data[key];
for (var innerKey in data[key]) {
modData[key] = data[key];
}
}
}
console.log("Modified is:", modData);
Unfortunately, this still returns the original object, what is it that I am doing which is wrong?
A jquery solution is fine as well.
Loop trough the properties with for .. in and any property is not an object replace it with one. Like this:
let x = {
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
}
for (key in x.Results) {
if (typeof x.Results[key] !== 'object')
x.Results[key] = {
[key]: x.Results[key]
}
}
console.log(x);
If you want to preserve the original object do this:
let data = {
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
}
data = data.Results;
modData = {};
for (key in data) {
if (typeof data[key] !== 'object')
modData[key] = { [key]: data[key] }
else
modData[key] = { [key]: data[key] }
}
console.log(modData);
You could check the type and if not an object then assign a new object with the same key and value.
This proposal uses computed property names for getting a variable as key for an object.
var object = { Results: { circle: 0.06879016757011414, quad: { exp: 0.8039023876190186, actual: 0.19609761238098145 }, square: 0.8266428709030151 } };
Object
.keys(object.Results)
.forEach(function (k) {
if (object.Results[k] && typeof object.Results[k] !== 'object') {
object.Results[k] = { [k]: object.Results[k] };
}
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The value that should be stored in modData should be the object itself rather than the value. This code gives the expected value
var modData = {};
data = data.Results;
for (var key in data) {
if (data.hasOwnProperty(key)) {
var temp = Object();
temp[key] = data[key];
modData[key] = temp;
for (var innerKey in data[key]) {
var temp = Object();
temp[key] = data[key];
modData[key] = temp;
}
}
}
const input = {
"Results": {
"circle": 0.06879016757011414,
"quad": {
"exp": 0.8039023876190186,
"actual": 0.19609761238098145
},
"square": 0.8266428709030151
}
};
const result = {
Results: {}
};
//If you want object construct specifically for "circle" & "square"
for (let key in input.Results) {
if (input.Results.hasOwnProperty(key)) {
if (key === 'circle') {
result.Results.circle = {
'circle': input.Results[key]
}
} else if (key === 'square') {
result.Results.square = {
'square': input.Results[key]
}
} else {
result.Results[key] = input.Results[key];
}
}
}
//Generically construct object if key is not object
for (let key in input.Results) {
if (input.Results.hasOwnProperty(key)) {
if (key !== 'object') {
result.Results[key] = {
[key]: input.Results[key]
}
}
}
}
console.log(result);