Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

54
Views
Create bracket notation from array of strings

I have an array of strings like this:

const deepProperties = ['contactPerson', 'firstName']

How can access the property contactPerson.firstName (get and set) of an anonymous object having this string array at hand?

const unknown = { contactPerson: { firstName: 'Jane' } }

I know I can do unknown['contactPerson']['firstName'] to get the value and unknown['contactPerson']['firstName'] = 'John' to set a new value - but how do I get there from the array?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use lodash get/set.

For example:

const get = require('lodash.get');
const set = require('lodash.set');

const deepProperties = ['contactPerson', 'firstName']
const unknown = { contactPerson: { firstName: 'Jane' } }

get(unknown, deepProperties.join("."))
// 'Jane'

set(unknown, deepProperties.join("."), "Mary")
// { contactPerson: { firstName: 'Mary' } }

Note that this would also work if the embedded properties included arrays, for example:

const props = ["users[1]", "name"];
const org = { users:[{name:"joe",age:21}, {name:"mary",age:29}] };

get(org, props.join("."));
// 'mary'
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.