我有一个对象数组:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
如何通过JavaScript将其转换为以下内容?
{
"11": "1100",
"22": "2200"
}
我有一个对象数组:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
如何通过JavaScript将其转换为以下内容?
{
"11": "1100",
"22": "2200"
}
当前回答
下面是如何动态地接受上面的字符串,并将其插入到一个对象:
var stringObject = '[Object { key="11", value="1100", $$hashKey="00X"}, Object { key="22", value="2200", $$hashKey="018"}]';
function interpolateStringObject(stringObject) {
var jsObj = {};
var processedObj = stringObject.split("[Object { ");
processedObj = processedObj[1].split("},");
$.each(processedObj, function (i, v) {
jsObj[v.split("key=")[1].split(",")[0]] = v.split("value=")[1].split(",")[0].replace(/\"/g,'');
});
return jsObj
}
var t = interpolateStringObject(stringObject); //t is the object you want
http://jsfiddle.net/3QKmX/1/
其他回答
使用reduce的简单方法
// Input :
const data = [{key: 'value'}, {otherKey: 'otherValue'}];
data.reduce((prev, curr) => ({...prev, ...curr}) , {});
// Output
{key: 'value', otherKey: 'otherValue'}
使用Object.assign更简单
Object.assign({}, ...array);
使用Object.fromEntries:
Const数组= [ {key: "key1", value: "value1"}, {key: "key2", value: "value2"}, ]; const obj = Object.fromEntries(array.map(item => [item. map])键,item.value])); console.log (obj);
使用Underscore.js:
var myArray = [
Object { key="11", value="1100", $$hashKey="00X"},
Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));
你可能正在寻找这样的东西:
/ /原始 Var arr = [ {key: '11',值:'1100',$$hashKey: '00X'}, {key: '22',值:'2200',$$hashKey: '018'} ]; / /转换 Var结果= {}; For (var I = 0;I < arrr .length;我+ +){ 结果(arr[我]。Key] = arr[i].value; } console.log(结果);
这应该做到:
Var数组= [ {key: 'k1', value: 'v1'}, {key: 'k2', value: 'v2'}, {键:'k3',值:'v3'} ]; Var mapped = array。Map (item => ({[item。关键:项目。Value})); var newObj =对象。分配({},……映射); console.log (newObj);
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));