【问题标题】:How to convert object key value pair with array as values to multi objects of key value pair?如何将具有数组作为值的对象键值对转换为键值对的多个对象?
【发布时间】:2020-07-19 06:39:40
【问题描述】:

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

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

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

{

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

有没有办法实现上述结构?我已经尝试了几种使用数组减少方法的方法,但它没有提供所需的输出。

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

【问题讨论】:

  • 新键应该是什么?键可以是任何字符串?
  • @SivakumarTadisetti。这可以是任何具体的。我们可以称它为 newObj。
  • 您不应该将其转换为以下形式的对象数组:[{status: "new", place: "york"}, {status: "old", place: "blah"}]

标签: javascript arrays object


【解决方案1】:

你可以这样做

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

【讨论】:

    【解决方案2】:

    这是一个使用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);

    【讨论】:

      【解决方案3】:

      这是我的实现方式。

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          这是在.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' }
            ]
          }
          */

          【讨论】:

            【解决方案6】:

            对于那些不了解 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)
            

            【讨论】:

              猜你喜欢
              • 2017-09-23
              • 2018-08-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多