简体   繁体   English

如何将某些对象键分成自己的数组?

[英]How can I separate certain object keys into their own array?

This is my first question on here. 这是我的第一个问题。 Doesn't appear to be asked elsewhere, but then again I'm not sure exactly how to phrase my question. 似乎没有在其他地方被问到,但是话又说回来,我不确定确切如何表达我的问题。

How can I transform an array that looks like this: 我该如何转换一个看起来像这样的数组:

var message = {
    pay_key: '12345',
    'transaction[0].sender_id': 'abc',
    'transaction[0].is_primary_receiver': 'false',
    'transaction[0].id': 'def',
    'transaction[1].sender_id': 'xyz',
    'transaction[1].is_primary_receiver': 'false',
    'transaction[1].id': 'tuv',
};

into something like this: 变成这样的东西:

{
pay_key : '12345',
transaction : [
    {
        sender_id : 'abc',
        is_primary_receiver : 'false',
        id : 'def'
    },
    {
        sender_id : 'xyz',
        is_primary_receiver : 'false',
        id : 'tuv'
    }
]
}        

I have no control over the format of the first object as it comes from an external service. 我无法控制第一个对象的格式,因为它来自外部服务。 I am trying to insert the message object into a MongoDB collection, but when I try to do an insert as-is, I get an error. 我试图将消息对象插入MongoDB集合中,但是当我尝试按原样进行插入时,出现错误。 So I'm trying to put it into the correct form. 因此,我正在尝试将其放入正确的表格中。

Should I be using Underscore for this? 我应该为此使用Underscore吗? I've played around with _.each but can't get it to work. 我玩过_.each,但是无法正常工作。

my take.. 我的看法

var message = {
    pay_key: '12345',
    'transaction[0].sender_id': 'abc',
    'transaction[0].is_primary_receiver': 'false',
    'transaction[0].id': 'def',
    'transaction[1].sender_id': 'xyz',
    'transaction[1].is_primary_receiver': 'false',
    'transaction[1].id': 'tuv',
};

message.transaction=[];
for (var p in message) {
  var m = p.match(/^transaction\[(\d+)\]\.(.*)/);
  if (m&&m[1]&&m[2]) {
    message.transaction[m[1]]=message.transaction[m[1]]||{};
    message.transaction[m[1]][m[2]]=message[p];
    delete message[p];
  }
}

Here's a generic function I just whipped up 这是我刚刚提到的通用函数

function makeObject(message) {
    var retObj = {},
        makePath = function (p, pos) {
            if (/\[\d+\]$/.test(p)) {
                var q = p.split(/[\[\]]/),
                    r = q[0],
                    s = q[1];
                if (!pos[r]) {
                    pos[r] = [];
                }
                return pos[r][s] = pos[r][s] || {};
            }
            return pos[p] = pos[p] || {};
        };
    for(var k in message) {
        if (message.hasOwnProperty(k)) {
            if (k.indexOf('.') < 0) {
                retObj[k] = message[k];
            }
            else {
                var path = k.split('.'),
                    pos = retObj,
                    last = path.pop();
                path.forEach(function(p) {
                    pos = makePath(p, pos);
                });
                pos[last] = message[k];
            }
        }
    }
    return retObj;
}

It works as required, but I'm sure there's some better code to do it 它可以按要求工作,但是我敢肯定有一些更好的代码可以做到

Had a similar response, so adding it anyway: 产生了类似的响应,因此无论如何都要添加它:

Object.keys(message).forEach(function(key) {
    var keySplit = key.split( /\[|\]\./g )
    if  ( keySplit.length != 1 ) {
        if ( !message.hasOwnProperty(keySplit[0]) )
            message[keySplit[0]] = [];
        message[keySplit[0]][keySplit[1]] = message[keySplit[0]][keySplit[1]]||{};
        message[keySplit[0]][keySplit[1]][keySplit[2]] = message[key];
        delete message[key];
    }
});

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

相关问题 React/MaterialUI - 如何在我的 object 中将每个 JSON 数组 map 放到它自己的单独表中? - React/MaterialUI - How can I map each JSON array in my object to it's own separate table? 如何用另一个 object 的密钥动态替换一个 object 中的某些密钥? - How can I dynamically replace certain keys in one object with keys from another object? 如何将数组值分配给其他对象的对象键? - How can I assign array values into object keys for other object? 如何从一个对象创建一个字符串数组,其中各个键的值是单独的字符串数组? - How do I create an array of strings from an object where the values of individual keys are separate arrays of strings? 如何获取存储在 Array 中的对象的键 - How can i get the keys of an object stored in Array 如何从javascript中的数组值创建对象键? - How can i create an object keys from array values in javascript? 如何使用键数组访问和更改对象中的值 - How can i access and change a value in an object with an array of keys 如何获取数组内的 object 的多个键 - How can I get multiple keys of an object that are inside an array 如何使用字符串/键数组访问 object 属性? - How can I access object properties using an array of strings / keys? 如何将具有相同键的对象数组合到一个对象中? - How can I combine an array of objects with the same keys into one object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM