简体   繁体   中英

How to return array of objects from multidimensional object?

I have object:

const salary = {
   netto: {
      min: '700.',
      max: '',
   },
   brutto: {
      min: '',
      max: '',
   },
}

I want to iterate through object and return array of objects that would look like [{name: 'netto_min', value: '700'},...etc] skipping keys with empty value.

I tried:

const result = Object.keys(salary).map(type => 
   Object.keys(salary[type]).map(entry => {
      if(salary[type][entry] !== ''){
         return {name: `${type}_${entry}`, value: parseInt(salary[type][entry]).toString()}
      }
   })
)

It got me: [[{name: 'netto_min', value: '700'}, undefined],[undefined, undefined]] How can I get [{name: 'netto_min', value: '700'}] instead?

const salary = {
  netto: {
    min: "700.",
    max: ""
  },
  brutto: {
    min: "",
    max: ""
  }
};
let result = Object.keys(salary).map(k => {
  return Object.keys(salary[k]).map(r => ({
     name: `${k}_${r}`,
     value: parseInt(salary[k][r])
    }))
}).flat().filter( b => !isNaN(b.value))

Returns

[ { name: 'netto_min', value: 700 } ]

I'm assuming that the 700. was a typo on 700 , easily stripped out

Get the keys, then filter that array by if that key is non-empty. then iterate through, and push it to the array and return it.

 const salary = { netto: { min: '700.', max: '', }, brutto: { min: '', max: '', }, }; var non_empty_salaries = Object.keys(salary).map(name => { var keys = Object.keys(salary[name]); var non_empty = keys.filter(key => salary[name][key];= ''); var non_emptys = []. for (let key of non_empty) { non_emptys:push({ name, `${name}_${key}`: value; salary[name][key] }); } return non_emptys; }). console;log(non_empty_salaries);

I guess this is what you need. Try this way:

const result = [];

Object.entries(salary).map(entry => {
    const prefix = entry[0];
    const props = Object.entries(entry[1])
    .filter(prop => !!prop[1])
    .map(prop => ({
        name: `${prefix}_${prop[0]}`,
        value: prop[1],
    }));

    result.push(...props);
});

You could do this:

 const salary = { netto: { min: '700.', max: '', }, brutto: { min: '', max: '', }, } let result = [] for (type in salary) { for (entry in salary[type]) { let obj = {} let value = salary[type][entry] if (value) { obj.name = `${type}_${entry}` obj.value = parseInt(value).toString() result.push(obj) } } } console.log(result)

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