Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 解析数组并将值转换为对象_Javascript_Arrays_Regex - Fatal编程技术网

Javascript 解析数组并将值转换为对象

Javascript 解析数组并将值转换为对象,javascript,arrays,regex,Javascript,Arrays,Regex,我有一个数组,我需要将其转换为具有给定值的对象 这是输入数组 let actions = ['CREATE: id=14&amount=800&currency=USD','FINALIZE: id=14&amount=800&currency=USD','PAY: id=14' ] 我怎样才能把它变成这个物体 let result ={ 'create': 800, 'finalize': 800, 'pay':14 } 到目前为止,我有一个循环来检

我有一个数组,我需要将其转换为具有给定值的对象

这是输入数组

let actions = ['CREATE: id=14&amount=800&currency=USD','FINALIZE: id=14&amount=800&currency=USD','PAY: id=14' 
]
我怎样才能把它变成这个物体

let result ={
 'create': 800,
 'finalize': 800,
 'pay':14
}
到目前为止,我有一个循环来检查数组中的键是否可用,但我在接下来的步骤中迷失了方向。一位同事说正则表达式可能是最好的选择

for(let x = 0; x <=actions.length;x++){
    if(actions[x].icludes('CREATE')){

    } else(actions[x].icludes('FINALIZE')){

    } else(actions[x].icludes('PAY')){

    }
}

for(设x=0;x您可以在
:\s+
处拆分每个字符串,以获得一个键和要分析的字符串。您将在结果数组中获得2个值。用于将它们用于分离变量

["CREATE", "id=14&amount=800&currency=USD"]
然后对第二个值使用构造函数从查询字符串中获取一个键值对

有些键需要
amount
,而有些键需要
id
的值。因此,您可以创建一个映射器对象。这将使用要在URLSearchParams中搜索的名称映射键

const mapper = {
  PAY: "id",
  CREATE: 'amount',
  FINALIZE: 'amount',
  default: "amount"
};
在这里,
PAY
需要
id
值。如果您有更多密钥,可以将其添加到这里。您可以添加
创建:“金额”
也可以添加到此对象。但是,由于这是
默认值
,因此我跳过了该操作。如果在
映射器中找不到键,则可以使用
默认值
键。从解析函数返回带有键和值的对象

然后创建数组并合并每个已解析的对象以创建输出

const actions=['CREATE:id=14&amount=800¤cy=USD','FINALIZE:id=14&amount=800¤cy=USD','PAY:id=14']
常量映射器={
支付:“身份证”,
//CREATE:'amount',//如果需要,可以添加CREATE和FINALIZE
默认值:“金额”
};
函数解析(str){
常量[key,value]=str.split(/:\s+/);
const param=新的URLSearchParams(value).get(映射器[键]| |映射器.default);
返回{[key.toLowerCase()]:param};
}
const output=actions.reduce((acc,str)=>Object.assign(acc,parse(str)),{});

console.log(output)
您可以在
:\s+
处拆分每个字符串,以获得一个键和要分析的字符串。您将在结果数组中获得2个值。用于将它们分离为单独的变量

["CREATE", "id=14&amount=800&currency=USD"]
然后对第二个值使用构造函数从查询字符串中获取一个键值对

有些键需要
amount
,而有些键需要
id
的值。因此,您可以创建一个映射器对象。这将使用要在URLSearchParams中搜索的名称映射键

const mapper = {
  PAY: "id",
  CREATE: 'amount',
  FINALIZE: 'amount',
  default: "amount"
};
在这里,
PAY
需要
id
值。如果您有更多密钥,可以将其添加到这里。您可以添加
创建:“金额”
也可以添加到此对象。但是,由于这是
默认值
,因此我跳过了该操作。如果在
映射器中找不到键,则可以使用
默认值
键。从解析函数返回带有键和值的对象

然后创建数组并合并每个已解析的对象以创建输出

const actions=['CREATE:id=14&amount=800¤cy=USD','FINALIZE:id=14&amount=800¤cy=USD','PAY:id=14']
常量映射器={
支付:“身份证”,
//CREATE:'amount',//如果需要,可以添加CREATE和FINALIZE
默认值:“金额”
};
函数解析(str){
常量[key,value]=str.split(/:\s+/);
const param=新的URLSearchParams(value).get(映射器[键]| |映射器.default);
返回{[key.toLowerCase()]:param};
}
const output=actions.reduce((acc,str)=>Object.assign(acc,parse(str)),{});

console.log(output)
考虑到您的预期输出不遵循单一结构,我选择返回所有值,而不是任意值。但是,如果您有一些业务逻辑来证明选择不同的值来返回是合理的,您可以轻松地更改代码以适应这种情况

const actions=[
“创建:id=14,金额=800,货币=USD”,
‘最终确定:id=14,金额=800,货币=USD’,
‘PAY:id=14’
];
const actionsData=actions.reduce((res,str)=>{
const[op,query]=str.split(“:”);
const kvPairs=query.split('&');
const data=kvPairs.reduce((res,kvStr)=>{
常量[key,value]=kvStr.split('=');
res[键]=值;
返回res;
}, {});
res[op]=数据;
返回res;
}, {});

console.log(actionsData);
考虑到您的预期输出不遵循单一结构,我选择返回所有值,而不是任意值。但是,如果您有一些业务逻辑来证明选择不同的值返回是合理的,您可以轻松地更改代码以适应这种情况

const actions=[
“创建:id=14,金额=800,货币=USD”,
‘最终确定:id=14,金额=800,货币=USD’,
‘PAY:id=14’
];
const actionsData=actions.reduce((res,str)=>{
const[op,query]=str.split(“:”);
const kvPairs=query.split('&');
const data=kvPairs.reduce((res,kvStr)=>{
常量[key,value]=kvStr.split('=');
res[键]=值;
返回res;
}, {});
res[op]=数据;
返回res;
}, {});

console.log(actionsData);
作为一个正则表达式示例,这也可以工作。当然,可能总是有一个更健壮的正则表达式规则。(并且更具可扩展性)


作为一个正则表达式的例子,这也是可行的。当然,可能总会有一个更健壮的正则表达式规则。(并且更具可扩展性)

这里有一个解决方案:

let actions = ['CREATE: id=14&amount=800&currency=USD','FINALIZE: id=14&amount=800&    currency=USD','PAY: id=14']
let actionObject = [];

for(let i=0;i<actions.length;i++){

    // Split where it has colon and space
    let splitter = actions[i].split(": ");

    // Get label (and make it lowercase)
    let theLabel = splitter[0].toLowerCase();

    // remove label from array
    splitter.splice(0,1);

    // rejoin array if any values contained colon and space
    splitter = splitter.join(": ");

    // find amount= and split that
    splitter2 = splitter.split("amount=");

    // splitter2[1] will be everything after "amount="
    // if amount= didn't exist it will be undefined
    if(splitter2[1] !== undefined){
        // Now we just split the other side of the amount where &
        // if amount is the last thing and there's no &, it won't matter
        splitter2 = splitter2[1].split("&");

        // Now create the key (l1) and value (splitter2[0])
        actionObject[l1] = splitter2[0];
    }else{
        // If amount is not found, we get id instead, same process
        splitter2 = splitter.split("id=");
        if(splitter2[1] !== undefined){
            splitter2 = splitter2[1].split("&");
            actionObject[l1] = splitter2[0];
        }
    }
}
这里有一个解决方案:

let actions = ['CREATE: id=14&amount=800&currency=USD','FINALIZE: id=14&amount=800&    currency=USD','PAY: id=14']
let actionObject = [];

for(let i=0;i<actions.length;i++){

    // Split where it has colon and space
    let splitter = actions[i].split(": ");

    // Get label (and make it lowercase)
    let theLabel = splitter[0].toLowerCase();

    // remove label from array
    splitter.splice(0,1);

    // rejoin array if any values contained colon and space
    splitter = splitter.join(": ");

    // find amount= and split that
    splitter2 = splitter.split("amount=");

    // splitter2[1] will be everything after "amount="
    // if amount= didn't exist it will be undefined
    if(splitter2[1] !== undefined){
        // Now we just split the other side of the amount where &
        // if amount is the last thing and there's no &, it won't matter
        splitter2 = splitter2[1].split("&");

        // Now create the key (l1) and value (splitter2[0])
        actionObject[l1] = splitter2[0];
    }else{
        // If amount is not found, we get id instead, same process
        splitter2 = splitter.split("id=");
        if(splitter2[1] !== undefined){
            splitter2 = splitter2[1].split("&");
            actionObject[l1] = splitter2[0];
        }
    }
}

你的解释非常直截了当。你的解释非常直截了当。你的解释非常直截了当。