简体   繁体   中英

How do I deal with an array of input strings and make them match to an objects array keys even if there is nesting?

https://codesandbox.io/s/lucid-bhaskara-fohmt

For example I have an array of strings:

let inputNames = ['name', 'address[city]', 'address[state]'];

with this sample error object:

  let errors = {
    name: {message:"error in name"},
    address: {
     city: {message:"error in address city"},
     state: {message:"error in address state"}
    }
  }

When looping through names I would like to check the error based on the input name:

  inputNames.forEach(n=> {
    if(typeof errors[n] !== 'undefined') {
      console.log(errors[n]);
    } else {
      console.log('SHOULD have returned value of', errors.address.city);
    }
  })

Keep it simple and use lodash's get function.

const {get} = require("lodash");

let inputNames = ['name', 'address.city', 'address.state'];

let errors = {
  name: {message:"error in name"},
  address: {
   city: {message:"error in address city"},
   state: {message:"error in address state"}
  }
}

inputNames.forEach(n=> {
  if(get(errors, n)) {
    console.log(get(errors, n));
  } else {
    console.log('SHOULD have returned value of', errors.address.city);
  }
})

OR you can use plain javascript to achieve this using this function

function get(obj, path) {
  return path.split('.').reduce((parent, child)=> parent && parent[child]||null, obj)
}

You can use lodash . _.get(obj, key, defaultVal)

 let inputNames = ['name', 'address[city]', 'address[state]']; let errors = { name: {message:"error in name"}, address: { city: {message:"error in address city"}, state: {message:"error in address state"} } }; console.log(_.get(errors, inputNames[1]))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM