How transform string to recursive object? [duplicate] - javascript

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'))

Related

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

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)

How change the name of property in array of objects good way? [duplicate]

This question already has answers here:
Changing the key name in an array of objects?
(11 answers)
Rename Object Key in an array using javascript
(6 answers)
How to rename key of object in an array
(4 answers)
Closed 1 year ago.
Now I have object like this
let arr = [{name:'first'},{name:'first1'}]
Exprected
[{value:'first'},{value:'first1'}]
My attempt
let result = arr.map(el=>{
const {name, ...other} = el;
return {value: el.name, ...other}
})
you can do it that way!
let arr = [{name:'first'},{name:'first1'}] //{value: 'first'}
let result = arr.reduce((acc,el)=>{
return [...acc, {'value' : el.name}]
},[])
You can transform the data using Array.prototype.map.
let arr = [{name:'first'},{name:'first1'}]
let result = arr.map(x => {return {value: x.name}});
console.log(result);

Attempting to retrieve only the values, not the keys [duplicate]

This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 2 years ago.
I am working on this code below. I am attempting to retrieve only the values, not the keys. What this is not doing is providing me with the values but the keys. Can you help me to get this to work properly?
Unfortunately I cannot use the object.values() function, therefore I am at a loss right now. Sorry This was not stated when I posted the original.
function values(obj) {
let arr = [];
for (let value in obj) {
arr.push(value);
}
return arr;
}
let nicknames = {a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`}
let nicknameValues = values(nicknames)
console.log(nicknameValues)
You can try:
arr.push(obj[value]);
Demo:
function values(obj) {
let arr = [];
for (let value in obj) {
arr.push(obj[value]);
}
return arr;
}
let nicknames = {a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`}
let nicknameValues = values(nicknames)
console.log(nicknameValues);
Or
const result = Object.values({a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`});
console.log(result);
Demo:
const result = Object.values({a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`});
console.log(result);
You can use Object.values:
const values = Object.values({a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`});
console.log(values);
Or you can change you function values
arr.push(obj[value]);

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