Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

javascript - Changing the key name in an array of objects?

How can I change the key name in an array of objects?

var arrayObj = [{key1:'value1', key2:'value2'},{key1:'value1', key2:'value2'}];

How can I change each key1 to stroke so that I get:

var arrayObj = [{stroke:'value1', key2:'value2'},{stroke:'value1', key2:'value2'}];
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In recent JavaScript (and TypeScript), use destructuring with rest syntax, spread syntax, and array map to replace one of the key strings in an array of objects.

const arrayOfObj = [{
  key1: 'value1',
  key2: 'value2'
}, {
  key1: 'value1',
  key2: 'value2'
}];
const newArrayOfObj = arrayOfObj.map(({
  key1: stroke,
  ...rest
}) => ({
  stroke,
  ...rest
}));

console.log(newArrayOfObj);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...