【问题标题】:How to expose objects to a given pattern?如何将对象暴露给给定的模式?
【发布时间】:2021-07-06 00:03:13
【问题描述】:

我以随机顺序自动生成一个对象数组。这意味着对象的初始顺序可以不同。

var a = [{account: true},{name: true},{amount: true},{address: true}];

var a = [{name: true},{account: true},{amount: true},{address: true}];

如何将对象暴露给给定的模式?

var a = [{amount: true},{address: true},{account: true},{name: true}];

如何将自动生成的元素每次以不同的顺序排列?我需要按顺序排列物品 - 金额、地址、帐户、姓名。

我有解决办法!

var order = [{account: true},{name: true},{amount: true},{address: true}];
var pattern = [{amount: true},{address: true},{account: true},{name: true}];

var sort = pattern.map(pattern => order.find(order => order[0] === pattern[0]));

console.log(sort); //[{amount: true},{address: true},{account: true},{name: true}]

【问题讨论】:

  • 我不立即同意重复关闭。请更新您的问题以包含Minimal, Complete, and Reproducible Code Example,以说明您已经尝试自己对数据进行排序,并更清楚地说明您想要什么,或者您要解决的问题是什么。 SO 不是代码编写服务。
  • 什么样的模式?
  • 如何将自动生成的元素按特殊顺序每次按不同的顺序排列?我需要按顺序排列物品 - 金额、地址、帐户、姓名?
  • 根据用户的操作,这些元素以不同的顺序排列。但最后,我需要按照指定的顺序带上这些元素——金额、地址、账户、姓名。你怎么能这样做?
  • 元素对象是否会拥有多个这些属性/键?对决胜局有偏好吗?再说一次,你是如何尝试自己解决这个问题的?

标签: javascript reactjs


【解决方案1】:

我无法使用您的代码进行正确排序。它似乎返回了一个数组,其中包含 order 数组的第一个元素的所有相同元素。

[{ account: true },{ account: true },{ account: true },{ account: true }]

const order = [
  { account: true },
  { name: true },
  { amount: true },
  { address: true }
];
const pattern = [
  { amount: true },
  { address: true },
  { account: true },
  { name: true }
];

var sort = pattern.map((pattern) =>
  order.find((order) => order[0] === pattern[0])
);

console.log("unsorted: ", JSON.stringify(order));
console.log("sorted:   ", JSON.stringify(sort));

这里有一个排序似乎可以对你的数组元素对象进行排序。

const sortedData = data.sort(
  (a, b) =>
    !!b.amount - !!a.amount ||
    !!b.address - !!a.address ||
    !!b.account - !!a.account ||
    !!b.name - !!a.name
);

这通过将未定义的值强制为布尔值(即未定义 -> false)然后通过再次强制布尔值类型为数字(true -> 1,false -> 0)来使用数值比较,从而导致排序[-1, 0, 1] 的比较器结果值。

const data = [
  { account: true },
  { name: true },
  { amount: true },
  { address: true }
];

console.log("unsorted: ", JSON.stringify(data));

const sortedData = data.sort(
  (a, b) =>
    !!b.amount - !!a.amount ||
    !!b.address - !!a.address ||
    !!b.account - !!a.account ||
    !!b.name - !!a.name
);

console.log("sorted:   ", JSON.stringify(sortedData));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-27
    • 2010-12-01
    • 2012-09-03
    • 2021-01-17
    • 1970-01-01
    • 2023-03-03
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多