undefinedfix
Sign in

How can Vue replace the key name of an array object?

zlodes edited in Fri, 30 Dec 2022

For example, I'm going to

[
    {'mingzi':'zhangsan','nianling':24},
    {'mingzi':'lisi','nianling':25}
]

The key name of such an array object is replaced and finally generated

[
    {'name':'zhangsan','age':24},
    {'name':'lisi','age':25}
]

What should we do?

4 Replies
toting
commented on Fri, 30 Dec 2022
let data = [{
    'mingzi': 'zhangsan',
    'nianling': 24
  },
  {
    'mingzi': 'lisi',
    'nianling': 25
  }
]
let result = data.map(item => ({
  name: item.mingzi,
  age: item.nianling
}));
console.log(result);
ecisse
commented on Sat, 31 Dec 2022
let arr = [
    {'mingzi':'zhangsan','nianling':24},
    {'mingzi':'lisi','nianling':25}
];
let newArr = JSON.parse(JSON.stringify(arr).replace(/mingzi/g, "name").replace(/nianling/g, "age"));
console.log(newArr);
bmccormick
commented on Sat, 31 Dec 2022

Create a new matching object

let matchObj = {
'mingzi': 'name',
'nianling: 'age'
}
let data = [{
    'mingzi': 'zhangsan',
    'nianling': 24
  },
  {
    'mingzi': 'lisi',
    'nianling': 25
  }
]
let result = data.map(item => ({
  [matchObj.mingzi]: item.mingzi,
  [matchObj.nianling]: item.nianling
}));
console.log(result);
vertuindiaofficial
commented on Sat, 31 Dec 2022

It's similar to the one above

let matchObj = {
  'mingzi': 'name',
  'nianling': 'age'
}
let data = [{
    'mingzi': 'zhangsan',
    'nianling': 24
  },
  {
    'mingzi': 'lisi',
    'nianling': 25
  }
]
let result = data.map(item => {
    let data = {};
    Object.entries(item).forEach(([k, v]) => {
      data[matchObj[k] || k] = v;
    });
    return data;
});
console.log(result);