简体   繁体   English

通过数组 JavaScript 内的 object 字段移动对象

[英]Move objects by object fields inside array JavaScript

I have an array of objects, that represents data from a chart.我有一个对象数组,代表图表中的数据。 I also have a varibale Timezone.我也有一个可变的时区。 How do I move objects that have sales > 0 according to the Timezone variable?如何根据时区变量移动销售额 > 0 的对象? So if Timezone = -5, all objects that have sales > 0 should move it's position -5 indexes.因此,如果 Timezone = -5,所有销售额 > 0 的对象都应该移动它的 position -5 索引。 The numbering of the name field should remain intact, from 12 to 1 and from 1 to 11, but sales move according to the Timezone variable.名称字段的编号应保持不变,从 12 到 1 和从 1 到 11,但销售额会根据时区变量移动。 在此处输入图像描述

You can do next:您可以执行以下操作:

  1. Create new array: const result = new Array(yourObjectsArr.length);创建新数组: const result = new Array(yourObjectsArr.length);
  2. Go through yourObjectsArr first time: Go 通过yourObjectsArr第一次:
yourObjectsArr.forEach((obj, key) => {
  if (obj.sales > 0) {
    // what if (key - timeZone) is negative?
    const result[key - timeZone] = obj;
  }
});
  1. Go through yourObjectsArr second time and deal with all cases when sales <= 0. Mb it'd possible to do it in one loop, depends on which position should occupied these objects Go 第二次通过yourObjectsArr并处理销售 <= 0 时的所有情况。Mb 可以在一个循环中完成,取决于哪个 position 应该占用这些对象

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

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