我有一个对象数组:
[
{ 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 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 arr = [{ key: "11", value: "1100" }, { key: "22", value: "2200" }];
var result = {};
for (var i=0, len=arr.length; i < len; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result); // {11: "1000", 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/
我喜欢用函数方法来完成这个任务:
var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
obj[item.key] = item.value;
return obj;
}, {});
注意:Last{}是reduce函数的初始obj值,如果你不提供初始值,第一个arr元素将被使用(这可能是不可取的)。
https://jsfiddle.net/GreQ/2xa078da/
使用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'));
微小的ES6解决方案可以看起来像:
var arr =[{关键:“11”,值:" 1100 "},{关键:“22”,值:" 2200 "}); Var对象= arr.reduce( (obj, item) =>对象。赋值(obj,{[项目。关键:项目。Value}), {}); console.log(对象)
同样,如果你使用对象扩展,它可以看起来像:
var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});
还有一个更快99%的解决方案是(在jsperf上测试):
var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
这里我们受益于逗号运算符,它计算逗号之前的所有表达式,并返回最后一个(在最后一个逗号之后)。因此,我们不是每次都复制obj,而是将新属性赋给它。
这应该做到:
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 }) )));
/ /原始 Var arr = [{ 关键:“11”, 价值:“1100”, $ $ hashKey: 00 x ' }, { 关键:“22”, 价值:“2200”, $ $ hashKey:“018” } ]; //我的解决方案 Var obj = {}; 对于(设I = 0;I < arrr .length;我+ +){ obj arr[[我]。Key] = arr[i].value; } console.log (obj)
使用现代JavaScript的一种干净的方法如下:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
使用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);
你可以使用mapKeys lodash函数。只有一行代码!
请参考这个完整的代码示例(复制粘贴到repl。它或类似):
import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');
let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
// '45': { id: 45, title: 'fish' },
// '71': { id: 71, title: 'fruit' } }
在2022年附近,我喜欢这种方法,特别是当对象数组是动态的时,这也是基于@AdarshMadrecha的测试用例场景的建议,
const array = [
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }];
let obj = {};
array.forEach( v => { obj[v.key] = v.value }) //assign to new object
console.log(obj) //{11: '1100', 22: '2200'}
let array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
let arr = {};
arr = array.map((event) => ({ ...arr, [event.key]: event.value }));
console.log(arr);
使用reduce的简单方法
// Input :
const data = [{key: 'value'}, {otherKey: 'otherValue'}];
data.reduce((prev, curr) => ({...prev, ...curr}) , {});
// Output
{key: 'value', otherKey: 'otherValue'}
使用Object.assign更简单
Object.assign({}, ...array);
是昨天做的
// Convert the task data or array to the object for use in the above form
const {clientData} = taskData.reduce((obj, item) => {
// Use the clientData (You can set your own key name) as the key and the
// entire item as the value
obj['clientData'] = item
return obj
}, {});