簡體   English   中英

如何將 object 鍵值對以數組為值轉換為鍵值對的多個對象?

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

我有一個 object 鍵值對及其值作為元素數組。

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

我正在嘗試將其轉換為鍵值對的多個數組對象,如下所示。

{

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

有沒有辦法實現上述結構? 我已經嘗試了幾種使用數組減少方法的方法,但它沒有提供所需的 output。

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

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

這是一個使用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);

這是在.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 和減少的人,這是一個相當幼稚的解決方案,但它會起作用:

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