如何使一个数组的对象的值成为另一个数组对象的键



假设我有一个这样的数组:

array1 = [
{date: '1', text: 'a'},
{date: '2', text: 'b'},
{date: '3', text: 'a'},
{date: '4', text: 'b'}
];
// text will be either 'a' or 'b'
// basically, here date denotes the dates of a month, so it could be up to 28 or 29 or 30 or 31

现在我想把这个数组转换成类似下面的数组

array2 = [
{1: '1'},
{2: '0'},
{3: '1'},
{4: '0'}
];
// For each value of array1, value of date (1,2,3,4) becomes keys here. If text was 'a', it should convert to '1' and if it was 'b', it should convert to '0'.

我该怎么做?

只需遍历Array1,检查文本是否为"a",然后存储1,否则存储0。

const array1 = [
{date: '1', text: 'a'},
{date: '2', text: 'b'},
{date: '3', text: 'a'},
{date: '4', text: 'b'}
];
let newArray = {};
for(let i=0; i<array1.length; i++){
if(array1[i]["text"] === 'a'){
newArray[array1[i]["date"]] = 1;
} else {
newArray[array1[i]["date"]] = 0;
}
}
console.log(newArray)

const array2 = array1.map(value => {
let newValue;
if(value.text === 'a') {
newValue = 1;
} else if(value.text === 'b') {
newValue = 0;
}
let newObj = {};
newObj[value.date] = newValue;
return newObj;
});

您可以将此代码用于您试图实现的输出。

您可以使用一个mapper对象,该对象将text值映射到数字。然后在阵列上使用map

const array = [{date:"1",text:"a"},{date:"2",text:"b"},{date:"3",text:"a"},{date:"4",text:"b"}],
mapper = { a: '1', b: '0' },
output = array.map(o => ({ [o.date]: mapper[o.text] }))
console.log(output)

一个简单的单行线是:

const array1 = [
{date: '1', text: 'a'},
{date: '2', text: 'b'},
{date: '3', text: 'a'},
{date: '4', text: 'b'}
];
const array2 = array1.map(({date, text}) => ({[date]: text === "a" ? "1" : "0"}))
console.log(array2)

最新更新