这是我们的对象:
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"]
}
我想根据属性名称将数组元素移动到数组的末尾。
所需的结果将是:
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"]
}
答案 0 :(得分:2)
使用Object.entries()
将对象转换为[键,值]对的数组。映射数组,并针对每对,检查键(k
)在值(v
)中的索引。如果找到索引,请将键移到值的末尾。通过Object.fromEntries()
将数组转换回对象。
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)
如果始终在值中找到键,则可以始终对其进行过滤,并将其添加到数组的末尾:
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)