Javascript: how to dynamically create nested objects using object names given by an array
function assign(obj, keyPath, value) {
lastKeyIndex = keyPath.length-1;
for (var i = 0; i < lastKeyIndex; ++ i) {
key = keyPath[i];
if (!(key in obj)){
obj[key] = {}
}
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
Usage:
var settings = {};
assign(settings, ['Modules', 'Video', 'Plugin'], 'JWPlayer');
Dynamically add nested object, allocate given value and add further object using object with key-value pairs
Similar to above answers, but might be easier to read for the user who asked the question.
Assuming you are using ES6, you can loop through an object using the Object.keys() function and .forEach.
Object.keys() will return an array of keys for an object, and you can call forEach() on that array.
var basis = { a: '1', b: '2', c: '3', d: '4' }
var nestedKeys = { a: 'e', b: 'f', c: 'g', d: 'h', e: 'i', f: 'j', g: 'k' }
Object.keys(basis).forEach(function (basisKey) {
Object.keys(nestedKeys).forEach(function (matchedKey) {
if (basisKey == matchedKey) {
basis[basisKey] = [{
[nestedKeys[matchedKey]] : basis[basisKey],
'date' : Date.now(),
}];
}
});
});
console.log(JSON.stringify(basis, null, 4));
How to dynamically add data from an array with objects to a nested array?
You can add the pattern and label in your forEach and any other logic that you might need to transform the data.
const data = [{key: 'firstName', pattern: "{{firstName}}", label: "First Name"},
{key: 'lastName', pattern: "{{lastName}}", label: "Last Name"},
{key: 'unsubscribeLink', pattern: "{{unsubscribeLink}}", label: "Unsubscribe Link"}
]
const transformDataToTagsObject = (dData) => {
const dynamicData = {};
dData.forEach((currentData, index) => {
const currentKey = currentData.key
const name = currentData.label
let value = currentData.pattern
if(currentData.key === 'unsubscribeLink'){
value = `<a href='${value}'>Unsubscribe</a>`
}
dynamicData[currentKey] = {
name,
value
}
})
const tagsObject = {
tags: dynamicData
}
return tagsObject;
}
const finalResults = transformDataToTagsObject(data)
console.log(finalResults)
How does this function create a nested object?
The difference is that you didn't save a variable with a reference to the original object. When you reassign obj
, you no longer have a variable containing the parent.
When using the function, that variable is in the function caller. Reassigning the local variable obj
has no effect on the caller's variable.
To emulate this in your manual steps, change the beginning to:
const original = {};
let obj = original;
This is analogous to the way the function parameter is passed.
Then at the very end, do
console.log(JSON.stringify(original));
and you should see the whole object with all the nested properties added.
Dynamically set property of nested object
This function, using the arguments you specified, should add/update the data in the obj
container. Note that you need to keep track of which elements in obj
schema are containers and which are values (strings, ints, etc.) otherwise you will start throwing exceptions.
obj = {}; // global object
function set(path, value) {
var schema = obj; // a moving reference to internal objects within obj
var pList = path.split('.');
var len = pList.length;
for(var i = 0; i < len-1; i++) {
var elem = pList[i];
if( !schema[elem] ) schema[elem] = {}
schema = schema[elem];
}
schema[pList[len-1]] = value;
}
set('mongo.db.user', 'root');
Dynamically create nested javascript objects with the same key but different values from an array
Below code does what you want:
var data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]]const value = data.reverse().reduce((acc, item) => { return [{ ...item[0], name: acc }]});
console.log(value);
Create a dynamic nested object from array of properties
You could use reduce
:
var array = ['opt1','sub1','subsub1','subsubsub1'];var object = {};array.reduce(function(o, s) { return o[s] = {}; }, object);console.log(object);
How to simplify an array of objects with dynamic key names and a nested array into a simpler format?
Here's one way you could use a reducer to do it. It loops through the data array, taking each players object and combining it into the final array in the format you requested.
const reducer = (previousValue, currentValue,index) => {
let current = {}
currentValue.winRatio.forEach( (x, index) => {
current = previousValue[index] ?? { index };
current[currentValue.name] = x
previousValue[index] = current
})
return previousValue
}
data.reduce(reducer, [])
As to your two notes, the output is an array so it should know its index, but you could add a line to the forEach block in this example adding an index key/value pair if one doesn't exist yet as you loop through. For your second note, I'm not sure how to figure that out without just sorting the array (or going through it and noting the longest winRatio length) first, so I guess you could just do that.
Dynamically Change object value according to an Array of keyname in Javascript
it would be a setValue function.
const alfa = {};
const keyNames = ["bravo", "charlie"];
function setValue(target,keyPath,value){
[target,...keyNames].reduce((object,keyName) => {
if( keyName === keyPath[keyPath.length-1] ){
object[keyName] = value;
}
object[keyName] = object[keyName] || {};
return object[keyName]
})
}
setValue(alfa,keyNames,"oboo")
Related Topics
Http Status Code 401 Even Though I'm Sending Credentials in the Request
Origin <Origin> Is Not Allowed by Access-Control-Allow-Origin
How to Terminate the Script in JavaScript
How to Clone HTML Element Objects in JavaScript
Differencebetween the Different Scroll Options
Binding Multiple Events to a Listener (Without Jquery)
Shrink Div to Text That's Wrapped to Its Max-Width
Best JavaScript Solution for Client-Side Form Validation and Interaction
Show a Second Dropdown Based on Previous Dropdown Selection
Why Is It Object.Defineproperty() Rather Than This.Defineproperty() (For Objects)
Ternary Operators in JavaScript Without an "Else"
How to Wait for a JavaScript Promise to Resolve Before Resuming Function
How to Insert a Character After Every N Characters in JavaScript
Limited Parallelism with Async/Await in Typescript/Es7
How to Convert an Iso Date to the Date Format Yyyy-Mm-Dd
Why Is the Variable Holding the Input Value Always Logged as Empty
Create a String of Variable Length, Filled with a Repeated Character