arr.splice 在所有可用索引中插入索引

arr.splice index inserts in all available indexes

        const list = []
        const obj = {
          name: '',
          mobile: ''
        }
        _.forEach(errors, (value, key) => {
          // eslint-disable-next-line no-debugger
          // debugger
          const field = key.split('.')[2]
          const index = key.split('.')[1]
          obj[field] = value[0]
          list.splice(index, 1, obj)
          console.log(obj)
        })

以上是我正在处理的代码。下面是每个 obj 变量

的日志截图

我想要的是将该对象插入到 list 变量的 index 中。

但是循环完成后我得到的是

循环中的最后一项会覆盖 list 数组中的所有内容。

下面顺便展示了index

总而言之,我需要将 obj 插入到 list 数组中的特定 index

编辑

errors 变量看起来像这样

我需要它看起来像这样。

list = [
   { name: 'name error message here', mobile: 'error message here' },
   { name: 'name error message here', mobile: 'error message here' },
   { name: 'name error message here', mobile: 'error message here' },
   { name: 'name error message here', mobile: 'error message here' }
]

问题是您在 forEach 循环外创建了 obj,并为 errors 中的所有元素插入相同的 obj。如果您随后更新 obj 您将更新所有元素,因为所有元素都是对同一对象的引用。如果您希望每个 index 都有自己的对象,您应该在代码中反映出来。

const errors = {
  "contacts.0.mobile": ["Error. Mobile number is a required field."],
  "contacts.0.name":   ["Error. Contact name is a required field." ],
  "contacts.1.mobile": ["Error. Mobile number is a required field."],
  "contacts.1.name":   ["Error. Contact name is a required field." ],
};

const list = [];
_.forEach(errors, (value, key) => {
  const [, index, field] = key.split(".");
  if (!list[index]) list.splice(index, 1, {name: "", mobile: ""});
  list[index][field] = value[0];
});

console.log(list);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

以上将为遇到的每个新 index 创建一个新对象。

这是你想要的吗?

function transform(data) {  
  return Object.entries(data).reduce((p, [key, [message]]) => {
    const keyElements = key.split('.')
    p[keyElements[1]] = p[keyElements[1]] || {}
    p[keyElements[1]][keyElements[2]] = message
    return p
  }, [])
}

const data = {
  'contacts.0.mobile': ["Error. Mobile number is a required field."],
  'contacts.0.name': ["Error. Contact name is a required field."],
  'contacts.1.mobile': ["Error. Mobile number is a required field."],
  'contacts.1.name': ["Error. Contact name is a required field."]
}
console.log(transform(data))

或者使用正则表达式和命名捕获组:

   
const PATTERN = /contacts.(?<index>\d+).(?<type>\w+)/

function transform(data) {  
  return Object.entries(data).reduce((p, [key, [message]]) => {
    const { index, type } = PATTERN.exec(key).groups
    p[index] = p[index] || {}
    p[index][type] = message
    return p
  }, [])
}

const data = {
  'contacts.0.mobile': ["Error. Mobile number is a required field."],
  'contacts.0.name': ["Error. Contact name is a required field."],
  'contacts.1.mobile': ["Error. Mobile number is a required field."],
  'contacts.1.name': ["Error. Contact name is a required field."]
}
console.log(transform(data))