javascript按字符串数组对对象数组进行排序

时间:2019-07-15 14:44:42

标签: javascript arrays sorting javascript-objects

有些数据结构没有索引:

const data = [{
        "B": {
            "value": 1,
        },
        "D": {
            "value": "45"
        },
        "E": {
            "value": "234"
        },
        "A": {
            "value": "543"
        },
        "C": {
            "value": "250"
        }
    }, {
        "B": {
            "value": 6,
        },
        "D": {
            "value": "234"
        },
        "E": {
            "value": "67"
        },
        "A": {
            "value": "78"
        },
        "C": {
            "value": "12"
        }
    }
   ]

以及上面的数据数组应按其排序的字符串数组:

const strings = ["E", "C", "B", "A", "D"];

是否有一种解决方案,可以按字符串对数据数组进行排序,以获得最终结果,如:

   [{
        "E": {
            "value": "234",
        },
        "C": {
            "value": "45"
        },
        "B": {
            "value": 1
        },
        "A": {
            "value": "543"
        },
        "D": {
            "value": "250"
        }
    }...

1 个答案:

答案 0 :(得分:-4)

是的,实际上非常简单。

const data = [{
        "B": {
            "value": 1,
        },
        "D": {
            "value": "45"
        },
        "E": {
            "value": "234"
        },
        "A": {
            "value": "543"
        },
        "C": {
            "value": "250"
        }
    }, {
        "B": {
            "value": 6,
        },
        "D": {
            "value": "234"
        },
        "E": {
            "value": "67"
        },
        "A": {
            "value": "78"
        },
        "C": {
            "value": "12"
        }
    }
   ]

const strings = ["E", "C", "B", "A", "D"];

const sorted = data.map(obj => {
  const res = {};
  strings.forEach(key => res[key] = obj[key]);
  return res;
});

console.log(sorted);

但是,javascript不能保证对象内部变量的顺序,因此您不应依赖它。要对其进行排序,必须使用数组,即数组,它不会是完全相同的数据结构,但它是相似的,并且可以确保排序。

const data = [{
        "B": {
            "value": 1,
        },
        "D": {
            "value": "45"
        },
        "E": {
            "value": "234"
        },
        "A": {
            "value": "543"
        },
        "C": {
            "value": "250"
        }
    }, {
        "B": {
            "value": 6,
        },
        "D": {
            "value": "234"
        },
        "E": {
            "value": "67"
        },
        "A": {
            "value": "78"
        },
        "C": {
            "value": "12"
        }
    }
   ]

const strings = ["E", "C", "B", "A", "D"];

const sorted = data.map(obj => {
  const res = [];
  strings.forEach(key => {
    const newObj = {};
    newObj[key] = obj[key];
    res.push(newObj)
  });
  return res;
});

console.log(sorted);

相关问题