英文:
How to format a particular value in array of object in javascript?
问题
以下是翻译好的部分:
"Hi I am getting some data from api and one particular value need to be in proper way. Can you please provide some kind of solution for this ?"
"我正在从 API 获取一些数据,其中一个特定的值需要以正确的方式呈现。您能提供一些解决方案吗?"
const data = [
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
const expectedData = [
{ state: 'Test', response: "ABC" },
{ state: 'Test', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
希望这能帮助您解决问题。
英文:
Hi I am getting some data from api and one particular value need to be in proper way. Can you please provide some kind of solution for this ?
const data = [
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
Below should be expected data after format, need to remove the number from state which start from (-) if it is exist
const expectedData = [
{ state: 'Test', response: "ABC" },
{ state: 'Test', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
答案1
得分: 0
你可以尝试映射数组,将文本按“-”分割并获取分割前的部分,就像这样:
const data = [
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
const formatted = data.map(data => ({...data, state: data.state.split("-")[0]}));
console.log(formatted);
英文:
You can try mapping the array, splitting the text in "-" and get what comes before it, like this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
const formatted = data.map(data => ({...data, state: data.state.split("-")[0]}))
console.log(formatted)
<!-- end snippet -->
答案2
得分: 0
const data = [
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
// pure
const result = data.map(({state, ...props}) => ({state: state.replace(/-[\d.]+$/, ''), ...props}));
console.log(JSON.stringify(result));
// mutable
data.forEach(item => item.state = item.state.replace(/-[\d.]+$/, ''));
console.log(JSON.stringify(data));
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];
// pure
const result = data.map(({state, ...props}) => ({state: state.replace(/-[\d.]+$/, ''), ...props}));
console.log(JSON.stringify(result));
// mutable
data.forEach(item => item.state = item.state.replace(/-[\d.]+$/, ''));
console.log(JSON.stringify(data));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论