简体   繁体   中英

Irrespective of keys need to push values into array

Here keys may come dynamic. so i need to get values only irrespective of keys.

 var test = [] var arrayObj = [ { "abc": { "value": "1" }, "def": { "value": "TERN" }, "aec": { "value": "SASU" }, "rtg": { "value": "FI" }, "ttyg": { "value": "9" }, "yty": { "value": "uyMFG" } }, { "abc": { "value": "1" }, "def": { "value": "EXT" }, "aec": { "value": "SAM" }, "rtg": { "value": "FINISH" }, "ttyg": { "value": "5" }, "yty": { "value": "MFG" } }] function printValues(obj) { for (var key in obj) { if (typeof obj[key] === "object") { printValues(obj[key]); } else { test.push(obj[key]) } } } printValues(arrayObj); console.log(test);

Am getting this

["1","TERN","SASU","FI","9","uyMFG","1","EXT","SAM","FINISH","5","MFG"]

but, i need to get as below output

[["1","TERN","SASU","FI","9","uyMFG"],["1","EXT","SAM","FINISH","5","MFG"]]

Am i doing in the right way or i can get better way than my approach ? Please suggest me how to achieve this. I don't know where i am going wrong.

If you don't particularly need the funciton to be recursive, you can achieve this with some Object and Array methods.

 var arrayObj=[{abc:{value:"1"},def:{value:"TERN"},aec:{value:"SASU"},rtg:{value:"FI"},ttyg:{value:"9"},yty:{value:"uyMFG"}},{abc:{value:"1"},def:{value:"EXT"},aec:{value:"SAM"},rtg:{value:"FINISH"},ttyg:{value:"5"},yty:{value:"MFG"}}]; const output = arrayObj.map(obj => { return Object.values(obj).map(({value}) => value) }) console.log(output);

In simplest form you can map the array and return a map of the Object.values().

This assumes the depth is known (as per example) and the value property is consistent

 const res = arrayObj.map(e => Object.values(e).map(o => o.value)) console.log(res)
 <script> var arrayObj=[{abc:{value:"1"},def:{value:"TERN"},aec:{value:"SASU"},rtg:{value:"FI"},ttyg:{value:"9"},yty:{value:"uyMFG"}},{abc:{value:"1"},def:{value:"EXT"},aec:{value:"SAM"},rtg:{value:"FINISH"},ttyg:{value:"5"},yty:{value:"MFG"}}]; </script>

You should not use for..in on arrays.

Use for..of on iterables like an array, string, etc

Use for..in on objects.

 var arrayObj = [ { abc: { value: "1" }, def: { value: "TERN" }, aec: { value: "SASU" }, rtg: { value: "FI" }, ttyg: { value: "9" }, yty: { value: "uyMFG" }, }, { abc: { value: "1" }, def: { value: "EXT" }, aec: { value: "SAM" }, rtg: { value: "FINISH" }, ttyg: { value: "5" }, yty: { value: "MFG" }, }, ]; var test = []; function printValues(arr) { for (var obj of arr) { const temp = []; for (let key in obj) { temp.push(obj[key].value); } test.push(temp); } } printValues(arrayObj); console.log(test);

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