How to convert string to object in object in js? [duplicate] - javascript

This question already has answers here:
How to create a nested object given an array of keys
(5 answers)
Closed 1 year ago.
I have a string: 'lorem,ipsum,dolor,sit,amet'
And I want to write a function with a parameter that converts this string passed as a parameter to an object like this:
{
lorem:{
ipsum:{
dolor:{
sit:{
amet: []
}
}
}
}
}

Split the string, and use Array.reduceRight() to generate the object:
const fn = (str, param) =>
str.split(',')
.reduceRight((acc, key) => ({ [key]: acc }), param)
const str = 'lorem,ipsum,dolor,sit,amet'
const result = fn(str, [])
console.log(result)

Related

How transform string to recursive object? [duplicate]

This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I am passing a dot separated string into function
console.log( namespace('a.b.c.d.e'))
and expect get next result
//result => "{"a":{"b":{"c":{"d":{"e":{}}}}}}"
my try (I don't know how to do it recursively)
const namespace = (string)=> {
return string.split('.').reduce((acc,el)=>{
acc[el] = {}
},{})
}
const input = "a.b.c.d.e"
const output = input.split('.').reverse().reduce((acc,el)=>{
return {[el]: acc}
},{})
console.log(output)
How about the below iteration approach :-
function namespace(input){
let result = {};
let temp = result;
const inputArr = input.split(".");
inputArr.forEach((ele)=>{
temp[ele] = {};
temp = temp[ele];
})
return result;
}
console.log( namespace('a.b.c.d.e'))

Assign javascript array to list of JSON objects with a property name? [duplicate]

This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
Closed 3 years ago.
I would like to convert a javascript array which looks like:
['https://www.google.com', 'https://www.facebook.com']
to a list of JSON objects that looks like this:
[{"redirectUri": "https://www.google.com"},
{"redirectUri": "https://www.facebook.com"}]
I have tried using Object.assign({}, array);
however this retuns json with the parameter name as the index of the array value and are all in a single object:
{"0": "https://www.google.com", "1": "https://www.facebook.com"},
is there a way to change this to use a custom parameter name dynamically?
You just need to map your elements respectively, using Array.map() method:
let result = arr.map(o => {
return {
"redirectUri": o
}
});
Demo:
let arr = ['https://www.google.com', 'https://www.facebook.com'];
let result = arr.map(o => {
return {
"redirectUri": o
}
});
console.log(result);

Finding a string in an array of strings [duplicate]

This question already has answers here:
Filter strings in Array based on content (filter search value)
(6 answers)
Closed 4 years ago.
I have an array of strings (names) such as:
name =["John Doe","Lutfur Kabir", "Moshiur Imtiaz Rahman", "Clark Kent","Jenny Doe"]
I want to get the index/es of the name that has Doe in it. How do I go about doing it using JavaScript.
You can use Array.prototype.includes:
Find the previous answer here already
var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];
var foundPresent = categoriesPresent.includes('specialword');
var foundNotPresent = categoriesNotPresent.includes('specialword');
console.log(foundPresent, foundNotPresent); // true false
You can use .reduce() to create an array having indexes of strings containing the desired string:
let data =["John Doe","Lutfur Kabir", "Moshiur Imtiaz Rahman", "Clark Kent","Jenny Doe"];
let result = data.reduce((r, c, i) => {
if(c.includes('Doe')) { r.push(i); }
return r;
}, []);
console.log(result);

Convert JavaScript dotted string in an object [duplicate]

This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Generic solution to create an Object of unknown deepth from an Array
(1 answer)
Closed 5 years ago.
Given a JS string: var s = "deep.deeper.deepest", how can I convert this into object like this: deep: {deeper: {deepest: {}}}
const dottedToObj = (str, orig = {}) => (str.split(".").reduce((obj, key) => obj[key] = {}, orig), orig);
Just reduce the array of strings (splitted the original string) into a chain of objects. Or a bit less functional:
function dottedToObj(str){
const root = {};
var acc = root;
for(const key of str.split(".")){
acc = acc[key] = {};
}
return root;
}
A simple loop should work for this, just move through each dotted property while moving down one level in the object:
const s = "deep.deeper.deepest";
function convertToObject(str) {
const result = {};
let inner = result;
for (const key of s.split(".")) {
// Give the object a child with this key
inner[key] = {};
// Set the current object to that child.
inner = inner[key]
}
// Return the original
return result;
}
console.log(convertToObject(s))

How to convert an object of key values to an array of objects [duplicate]

This question already has answers here:
How to transpose a javascript object into a key/value array
(11 answers)
Closed 5 years ago.
I want to convert an object of key values to an array of objects in javascript
var obj={"name1":"value1","name2":"value2",...};
How can i convert it to
arr=[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"},...];
Try with array#map and Array#push
var obj={"name1":"value1","name2":"value2"};
var res=[];
Object.keys(obj).map(a => res.push({name:a , value:obj[a]}))
console.log(res)
Short answer (ES6):
const arr = Object.entries(obj).map(([name, value]) => {
return {
name,
value
}
});
Another answer (ES5):
var arr = Object.keys(obj).map(function(key) {
return {
name: key,
value: obj[key]
}
});

Categories