如何将数组为值的对象键值对转换为键值对的多个对象



我有一个具有键值对的对象,它的值是元素数组。

{
status: ["new", "old"],
place: ["york", "blah"]
}

我正在尝试将它转换为键值对的多个数组对象,如下所示。

{
"newObj1": [
{ "status": "new" },
{ "status": "old" }],
"newObj2": [
{ "place": "york" },
{ "place": "blah" }]
}

有什么方法可以实现上述结构吗?我已经尝试了几个使用数组reduce方法的方法,但它没有提供所需的输出。

let value= {
status: ["new", "old"],
place: ["york", "blah"]
}
Object.keys(value).map((key) => [key, value[key]]);

您可以执行类似的操作

const obj = {
status: ["new", "old"],
place: ["york", "blah"]
};
const result = {};
Object.keys(obj).forEach((key, index) => {
result[`newObj${index + 1}`] = obj[key].map(item => ({[key]: item}));
});
console.log(result);

下面是一个使用Array.reduce():的解决方案

const value = {
status: ["new", "old"],
place: ["york", "blah"]
};
const result = Object.keys(value).reduce((acc, key, i) => {
acc["newObj" + (i + 1)] = value[key].map(k => ({ [key]: k }));
return acc;
}, {});
console.log(result);

以下是我实现这一点的方法。

let source = {
status: ["new", "old"],
place: ["york", "blah"]
};
let destination = {};  // make room for the destinoation object
Object.keys(source).forEach((key, index) => {
let obj = "newObj" + (index + 1);  // assume all objects are named "newObj1,2,3,etc"

if (!destination[obj]) {  // check if the object exists already
// if not, then crate an empty array first
destination[obj] = [];
}

// loop through all items in the source element array
source[key].forEach(value => {
// create an object from the array element
let subObj = {};
subObj[key] = value;

// push that object to the destination
destination[obj].push(subObj);
});
});
console.log(destination);

const data = {
status: ["new", "old"],
place: ["york", "blah"]
};
let result = Object.fromEntries( Object.entries(data).map( ([key, [first, second]], index) => {
return [ `newObj${index}`, [ { [key]: first }, { [key]: second } ] ];
} ) );
console.log(result);

以下是在.reduce:中使用.reduce的惯用解决方案

Object.entries(data)
.reduce((result, [key, value], index) => !(result['newObj' + (index + 1)] = value
.reduce((arr, text) => !arr
.push({ [key]: text }) || arr, [])) || result, {});

下面是一个活生生的例子:

const data = {
status: ['new', 'old'],
place: ['york', 'blah']
};
const result = Object.entries(data)
.reduce((result, [key, value], index) => !(result['newObj' + (index + 1)] = value
.reduce((arr, text) => !arr
.push({ [key]: text }) || arr, [])) || result, {});

console.log(result);
/*
{
newObj1: [
{ status: 'new' },
{ status: 'old' }
],
newObj2: [
{ place: 'york' },
{ place: 'blah' }
]
}
*/

对于那些不理解map和reduce的人,这里有一个相当天真的解决方案,但它会起作用:

newObjCounter = 1
orig = { status: [ 'new', 'old' ], place: [ 'york', 'blah' ] }
newObject = {}
//Initialise object with new keys with arrays as values
for(var key in orig){
newObject["newObj"+initialCounter] = []
initialCounter++
}
//Loop through keys of the original object and dynamically populate the new object
for(var key in orig){
index = "newObj"+objCounter
newObject[index].push({[key]:orig[key]})
objCounter++
}
console.log(newObject)

最新更新