0

I'm getting an object of objects from Firebase, but need to change the default items order. For that, I use Lodash orderBy() method.

computed: {
  sortedLogs() {
    return orderBy(this.logs, 'date', 'desc')
  }
},

The problem now is this method remove objects keys, and I need these keys to manage item delete request.

Original

{
    MFVMHJHnbpr: {
        date: 1598270895
        side: 'l'
    },
    MFVMblsdfdPb: {
        date: 1598270825
        side: 'r'
    },
    MsxvblsdfdPb: {
        date: 1598271225
        side: 'l'
    },
}

After orderBy()

{
    0: {
        date: 1598270895
        side: 'l'
    },
    1: {
        date: 1598270825
        side: 'r'
    },
    2: {
        date: 1598271225
        side: 'l'
    },
}
7
  • which keys? and how does the object look before et after applying that function? Commented Aug 24, 2020 at 18:18
  • 1
    Could you provide some sample data? I. e. what is in this.logs? An SO question should always contain a detailed description of the problem: What do you want to achieve (output) on the basis of which input? Commented Aug 24, 2020 at 18:19
  • @BoussadjraBrahim the key generated by Firebase for each entry in the database. After run the orderBy() method, the keys are replaced by an index sequence. Commented Aug 24, 2020 at 18:20
  • 1
    and how does the object look before et after applying that function? Commented Aug 24, 2020 at 18:20
  • 1
    check this, this might help: stackoverflow.com/questions/43112327/…
    – Syed
    Commented Aug 24, 2020 at 18:26

2 Answers 2

1

You can do it in plain JavaScript too, but if you want to rely on the order of elements you will have to convert the object to an array. Objects are not guaranteed to have a prescribed order in JavaScript (see here).

const inp= {
    MFVMHJHnbpr: {
        date: 1598270895,
        side: 'l'
    },
    MFVMblsdfdPb: {
        date: 1598270825,
        side: 'r'
    },
    MsxvblsdfdPb: {
        date: 1598271225,
        side: 'l'
    }
};
const out=Object.entries(inp).map(o=>(o[1].key=o[0],o[1])).sort((a,b)=>a.date-b.date)
console.log('Array:',out);

// alternatively, creating a "sorted object" - no guarantee!

const outObj=out.reduce((a,c)=>{let o={...c}; delete o.key; a[c.key]=o; return a;},{})
console.log('Object:',outObj);

0
0

orderBy does not mutate the original object, so you can just store a copy of this.logs and use that for deletion. This means, of course, you must also update the sortedLogs after you change the original data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.