简体   繁体   English

如何将 object 中的数组元素移动到数组末尾

[英]How to move array elements inside an object to end of the array

Here is our object:这是我们的 object:

let obj = {
  "I was sent":  ["I was sent", "I was forced"],
  "to earth": ["to earth", "to moon"],
  "to protect you": [ "to find you", "to protect you", "to love you"]

}

I want to move array elements based on the property name to the end of the array.我想将基于属性名称的数组元素移动到数组的末尾。

The desired result would be:期望的结果是:

  let obj = {
      "I was sent":  ["I was forced", "I was sent"],
      "to earth": ["to moon", "to earth"],
      "to protect you": [ "to find you", "to love you", "to protect you"]

    }

Use Object.entries() to convert the object to an array of [key, value] pairs.使用Object.entries()将 object 转换为 [key, value] 对的数组。 Map the array, and for each pair, check for the index of key ( k ) in the value ( v ). Map 数组,对于每一对,检查值 ( v ) 中键 ( k ) 的索引。 If the index is found, move the key to end of the value.如果找到索引,则将键移动到值的末尾。 Convert the array back to an object via Object.fromEntries() .通过Object.fromEntries()将数组转换回 object。

 const obj = { "I was sent": ["I was sent", "I was forced"], "to earth": ["to earth", "to moon"], "to protect you": [ "to find you", "to protect you", "to love you"] } const result = Object.fromEntries(Object.entries(obj).map(([k, v]) => { const index = v.findIndex(s => s === k) return [ k, index > -1? [...v.slice(0, index), ...v.slice(index + 1), k]: v ] })) console.log(result)

If the key is always found in the value, you can always filter it out, and add it to the end of the array:如果 key 总是在 value 中找到,你总是可以将其过滤掉,并将其添加到数组的末尾:

 const obj = { "I was sent": ["I was sent", "I was forced"], "to earth": ["to earth", "to moon"], "to protect you": [ "to find you", "to protect you", "to love you"] } const result = Object.fromEntries(Object.entries(obj).map(([k, v]) => { const newV = [...v.filter(s => s,== k), k] return [k. newV] })) console.log(result)

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

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