繁体   English   中英

Lodash从选定键创建新数组

[英]Lodash create new array from selected keys

我的道具数据输出为:

const { profile } = this.props;
console.log("help", profile);

{notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"}

我希望能够提取注释并最终得到如下结果:

{notes: "", notes2: "no notes", notes3: "no notes"}

我需要将“配置文件”保留为自己的道具,因此需要创建一个const来存储此输出。

我尝试过这样的事情:

const oldArray = _.map(_.toPairs(profile), d => _.fromPairs([d]));
const newArray = _.map(oldArray => [{notes: notes}, {notes: notes2}, {notes: notes3}]);

我要执行此操作的原因是然后运行检查以查看所有音符是否为空,但是当它们位于具有许多不同键的数组中时无法执行此操作。

如果有一个对象,则可以使用_.pick方法并返回具有特定属性的新对象。

 const obj = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"} const notes = _.pick(obj, ['notes', 'notes2', 'notes3']); console.log(notes) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script> 

您可以遍历该对象的键,并检查键是否具有notes作为子字符串。 如果是,则将该key-value添加到新对象。 使用此功能,您无需担心诸如notes1notes2notes3 ,...之类的键。 您可以简单地检查子字符串notes

 var obj = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", Notes2: "no notes", notes3: "no notes"}; var res = {}; Object.keys(obj).forEach((key) => { if(key.toLowerCase().indexOf('notes') !== -1){ res[key] = obj[key]; } }); console.log(res); 

您可以使用纯js而不是lodash:

const { profile } = this.props;
const { notes, notes2, notes3 } = profile;
const newObject  = { notes, notes2, notes3 };

然后,您可以检查值:

const hasValues = Object.values(newObject).filter(v => !!v).length > 0;

_.pickBy()String.startsWith() (或lodash的等效项 )一起使用,以查找所有以单词notes开头的键:

 const props = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"}; const notes = _.pickBy(props, (v, k) => k.startsWith('notes')); console.log(notes) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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