Convert a string to a nested JavaScript object or JSON [duplicate] - javascript

This question already has answers here:
Javascript nested objects from string
(5 answers)
Closed 1 year ago.
I have the following string:
let str = "modules.mas.mas-helper-provider.assets.locales";
and would like to convert it to a nested JavaScript object (JSON), something like this result:
{
"modules": {
"mas": {
"mas-helper-provider": {
"assets": {
"locales": ""
}
}
}
}
}

You can split the string to an array, then reduceRight to create an object by reading each key.
let str = "modules.mas.mas-helper-provider.assets.locales";
var newObject = str.split(".").reduceRight((obj, next) => ({
[next]: obj
}), "");
console.log(newObject);

Related

How to append JSON object to JSON object? [duplicate]

This question already has an answer here:
Dynamic object property names?
(1 answer)
Closed 8 months ago.
so i have this JSON file:
{"fjord-200-200.jpg":[]}
I read it using
let data = fs.readFileSync(cachedName);
let cachedInJSON: JSON = JSON.parse(data.toString());
so i have now JSON object, that i want to append to this new JSON object
let newData = {
fileNameFormatted: []
}
when i tried using
let newJson = {...cachedInJSON, ...newData}
Result was this:
{"fjord-200-200.jpg":[],"fileNameFormatted":[]}
Wanted result that i want to achieve is:
{"fjord-200-200.jpg":[],"fjord-300-300.jpg":[]}
fileNameFormatted is a variable holding fjord-300-300.jpg
let newData = {
[fileNameFormatted]: [] // Notice the brackets around the key
}

Check uniqueness with in nested object property values in array of objects [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I am returning null if an array of objects has the same property values and is fine with the direct object properties. I am trying with nested object property values in the same array, but it is failing. Below is the code for the same.
const getNullOrUniquePropertyValue = (arrToCheck, keyName, includeFullObject = null) => {
const uniqueValues = [...new Set(arrToCheck.map((v) => v[keyName]))];
if (uniqueValues.size !== 1) {
return null;
}
return includeFullObject ? arrToCheck[0].includeFullObject : arrToCheck[0].keyName;
};
And I am calling above function like as below
getNullOrUniquePropertyValue(
spaces,
'designHubProjectSpaceTypeId'
)
I am getting results as null for the above function because designHubProjectSpaceTypeId is not the same in the array.
I am passing nested objects property like as below, and it is returning null for below condition even if the array has both same values.
getNullOrUniquePropertyValue(spaces, 'spaceGeometry.ceilingHeight')
and the space structure like this as below
"spaces": [
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some Id"
},
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some other Id"
}
]
Could anyone please let me know where I am doing wrong with the above code?
Many thanks in advance!!
Some feedback:
v[keyName] isn't going to work if keyName is a string with a dot ("spaceGeometry.ceilingHeight"), you'll have to split the string and lookup the value at each level manually
uniqueValues is an array not a set, so use .length instead of .size
I made a simple function getNestedValue() that uses reduce to extract a nested value from an object.
const spaces = [
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some Id"
},
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some other Id"
}
];
const getNestedValue = (obj, path) => path.split(".").reduce((accum, key) => accum[key], obj);
const getNullOrUniquePropertyValue = (arrToCheck, keyName) => {
const uniqueValues = [...new Set(arrToCheck.map((v) => getNestedValue(v, keyName)))];
if (uniqueValues.length !== 1) {
return null;
}
return uniqueValues[0];
};
const result = getNullOrUniquePropertyValue(
spaces,
'spaceGeometry.ceilingHeight'
);
console.log(result);
I omitted includeFullObject from my example because it's not relevant to this particular issue, and I'm unclear what it's supposed to do. If you're having issues with that part too, let me know the details and I can help.

Converting a dynamic array into single object [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 years ago.
I have a dynamic array which is like this.
var callData = [
{
"FIELD_1": "0763454333"
},
{
"FIELD_2": "dgfdgfg"
},
{
"FIELD_3": "fgfdgfdg"
}
];
According to the user, these number of fields changes. If another user has more fields, there can be FIELD_4, FIELD_5 and so on. I fetch these data from db and put it into and array as above. Now I want to convert it a single object. I want it to look like this.
{
"FIELD_1": "076355998", "FIELD_2": "933504395v", "FIELD_3": "123"
}
Although I found converting solutions in stackoverflow, Those didn't solve my problem. How can I achieve this? Please guide.
use flatMap function to return entries of each object and then use Object.fromEntries function to create an object from the entries
var callData = [
{"FIELD_1": "0763454333" },
{ "FIELD_2": "dgfdgfg" },
{ "FIELD_3": "fgfdgfdg" }
];
const res = Object.fromEntries(callData.flatMap(o => Object.entries(o)));
console.log(res);

JSON object string to convert an array using map [duplicate]

This question already has answers here:
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
Closed 3 years ago.
Here is my response from my server.
var my_array = [{"1":"1"},{"2":"8"},{"4":"13"},{"5":"19"},{"6":"22"}]; //from server
I want to convert it like
var new_array = { 1 : "1", 2 : "8", 4 : "13", 5 : "19" , 6 : "22"}
But how to convert it using map function
new_array = my_array.map(function (a) {
return ???
});
Use reduce with spreading - you can't map an array to an object. Spreading also allows for multiple properties in each object.
var new_array = my_array.reduce((a, c) => ({ ...a, ...c }), {});
You could also use Object.fromEntries after flatMapping the entries:
var new_array = Object.fromEntries(my_array.flatMap(Object.entries));

Javascript to Group Array of Object into combination of two values [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Create Multilevel groups from an Array of Objects
(2 answers)
Closed 4 years ago.
var data=[
{custType:1,code:'savings',efDate:'2/3/19',exDate'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
];
expected results
var modifiedData=[
[
savings=[ {custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
],
current=[ {custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
],
[
savings=[ {custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'} ],
current=[ {custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
]
];
as i am trying to find a group with (custType and code), i am not able to generate the expected result. Which method i should use here? can i use reduce or groupBy. I am confused about it.
You could build up a nested hashtable:
const hash = {};
for(const value of data) {
const group = hash[value.custType] || (hash[value.custType] = {});
const group2 = group[value.code] || (group[value.code] = []);
group2.push(value);
}
const result = Object.values(hash).map(Object.values);

Categories

Resources