[英]remove non-selected keys from array of objects or create new array of objects with only selected value
[英]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
添加到新對象。 使用此功能,您無需擔心諸如notes1
, notes2
, notes3
,...之類的鍵。 您可以簡單地檢查子字符串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.