简体   繁体   中英

How to return values from a object matched by a array?

I am looking for the shortest way to get a new object as result from a existing object which matched all parts of a array.

Let me show what I mean:

This is the main-object
var mainobject={val1:text,val2:text,val3:text,val4:text,val5:text....};

now I want to get some of this entries like this

var only_some= get/function/what_i_need mainobject('val1','val3');

this will produce a new object with the matched parts from the mainobject

only_some.va1 = text
only_some.va3 = text

How can I do this?

You can access them like this, using the rest operator for arguments

 var mainobject = { val1: 'text1', val2: 'text2', val3: 'text3', val4: 'text4', val5: 'text5' }; function a(...args) { var obj={}; args.forEach((e) => { obj[e]=mainobject[e]; }) return obj; } console.log(a('val1', 'val4'));

 mainobject = { val1: "text1", val2: "text2", val3: "text3", val4: "text4", val5: "text5" }; function searchObj(value1, value2) { var resultObj = {}; for (var key in mainobject) { if (key == value1) { resultObj[value1] = mainobject[key]; } if (key == value2) { resultObj[value2] = mainobject[key]; } } return resultObj; } var only_some = searchObj("val1", "val3") console.log("result", only_some) console.log("result", only_some["val1"]) console.log("result", only_some["val3"])

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