简体   繁体   English

排序对象内部数组并返回对象

[英]Sort objects inner array and return object

If I have a object like this: 如果我有这样的对象:

const foo = {
    title: 'Bar',
    numbers: [1, 4, 3, 2],
}

I would like to sort foo.numbers and return the new foo object. 我想对foo.numbers进行排序并返回新的foo对象。

To sort the array is easy foo.numbers.sort((a, b) => b - a) 对数组进行排序很容易foo.numbers.sort((a, b) => b - a)

but this returns just the array. 但这只返回数组。

Is there anyway to return the parent object? 反正有返回父对象吗?

for example: 例如:

const newFoo = sortFooNumbers(foo);

console.log(newFoo);
---
{
    title: 'Bar',
    numbers: [1, 2, 3, 4],
}
const foo = {
    title: 'Bar',
    numbers: [1, 4, 3, 2],
}

function sortfoo(obj){
    obj.numbers.sort((a, b) => b - a)
    return obj
}

sortfoo(foo)
foo.numbers = foo.numbers.sort((a, b) => b - a)

You now have an updated foo with the sorted array. 现在,您具有带有已排序数组的更新的foo I'm assuming this is what you want. 我假设这就是您想要的。

Then you probably need to clone the object too: 然后,您可能还需要克隆对象:

const foo = {
  title: 'Bar',
  numbers: [1, 4, 3, 2],
};

function sortFoo(foo){
  const cloned = JSON.parse(JSON.stringify(foo));
  cloned.numbers.sort((a,b)=>a-b);
  return cloned;
}

const newFoo = sortFoo(foo);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM