简体   繁体   English

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

[英]How to convert object key value pair with array as values to multi objects of key value pair?

I have an object with key-value pair and its value as an array of elements.我有一个 object 键值对及其值作为元素数组。

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

I'm trying to convert it into multiple array objects of key-value pair like below.我正在尝试将其转换为键值对的多个数组对象,如下所示。

{

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

Is there any way to achieve the above structure?有没有办法实现上述结构? I have tried couple of methods using array reduce methods but it doesn't give in the desired output.我已经尝试了几种使用数组减少方法的方法,但它没有提供所需的 output。

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

You can do something like this你可以做这样的事情

 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);

 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);

Here's a solution that uses Array.reduce() :这是一个使用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);

Here is my way of accomplishing that.这是我实现这一目标的方法。

 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);

Here's an idiomatic solution using .reduce inside .reduce :这是在.reduce内部使用.reduce的惯用解决方案:

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

Here's a live example:这是一个活生生的例子:

 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' } ] } */

For those who fail to understand map and reduce, here's a fairly naive solution but it will work:对于那些无法理解 map 和减少的人,这是一个相当幼稚的解决方案,但它会起作用:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM