Related
I have an array of objects:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
How do I convert it into the following by JavaScript?
{
"11": "1100",
"22": "2200"
}
Tiny ES6 solution can look like:
var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = arr.reduce(
(obj, item) => Object.assign(obj, { [item.key]: item.value }), {});
console.log(object)
Also, if you use object spread, than it can look like:
var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});
One more solution that is 99% faster is(tested on jsperf):
var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
Here we benefit from comma operator, it evaluates all expression before comma and returns a last one(after last comma). So we don't copy obj each time, rather assigning new property to it.
This should do it:
var array = [
{ key: 'k1', value: 'v1' },
{ key: 'k2', value: 'v2' },
{ key: 'k3', value: 'v3' }
];
var mapped = array.map(item => ({ [item.key]: item.value }) );
var newObj = Object.assign({}, ...mapped );
console.log(newObj );
One-liner:
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));
You're probably looking for something like this:
// original
var arr = [
{key : '11', value : '1100', $$hashKey : '00X' },
{key : '22', value : '2200', $$hashKey : '018' }
];
//convert
var result = {};
for (var i = 0; i < arr.length; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result);
I like the functional approach to achieve this task:
var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
obj[item.key] = item.value;
return obj;
}, {});
Note: Last {} is the initial obj value for reduce function, if you won't provide the initial value the first arr element will be used (which is probably undesirable).
https://jsfiddle.net/GreQ/2xa078da/
Using Object.fromEntries:
const array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
const obj = Object.fromEntries(array.map(item => [item.key, item.value]));
console.log(obj);
A clean way to do this using modern JavaScript is as follows:
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" }
you can merge array of objects in to one object in one line:
const obj = Object.assign({}, ...array);
Use lodash!
const obj = _.keyBy(arrayOfObjects, 'keyName')
Update: The world kept turning. Use a functional approach instead.
Previous answer
Here you go:
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"}
Simple way using reduce
// Input :
const data = [{key: 'value'}, {otherKey: 'otherValue'}];
data.reduce((prev, curr) => ({...prev, ...curr}) , {});
// Output
{key: 'value', otherKey: 'otherValue'}
More simple Using Object.assign
Object.assign({}, ...array);
Using 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'));
Nearby 2022, I like this approach specially when the array of objects are dynamic which also suggested based on #AdarshMadrecha's test case scenario,
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);
Was did yesterday
// 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
}, {});
Here's how to dynamically accept the above as a string and interpolate it into an object:
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/
// original
var arr = [{
key: '11',
value: '1100',
$$hashKey: '00X'
},
{
key: '22',
value: '2200',
$$hashKey: '018'
}
];
// My solution
var obj = {};
for (let i = 0; i < arr.length; i++) {
obj[arr[i].key] = arr[i].value;
}
console.log(obj)
You can use the mapKeys lodash function for that. Just one line of code!
Please refer to this complete code sample (copy paste this into repl.it or similar):
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' } }
Is there a way I can iterate through each Oracle endpnt array and parse the strings to numbers and
still keep the Oracle endpnt arrays in order.
Code
var oracleTitle= ['oracle1','oracle2','oracle3','oracle4']
var oracleEndpnt = [['1','3'],['1','2'],['1','3'],[]]
function Oracle(name, endpnt) {
this.name = name;
this.endpnt = endpnt
}
var oracles = []
for(var i=0;i<oracleTitle.length;i++) {
oracles.push(new Oracle(oracleTitle[i],oracleEndpnt[i]))
}
console.log(oracles)
Result
[
Oracle { name: 'oracle1', endpnt: [ '1', '3' ] },
Oracle { name: 'oracle2', endpnt: [ '1', '2' ] },
Oracle { name: 'oracle3', endpnt: [ '1', '3' ] },
Oracle { name: 'oracle4', endpnt: [] }
]
If you dont want to change all the code, you can run a map for the second array
var oracleTitle= ['oracle1','oracle2','oracle3','oracle4']
var oracleEndpnt = [['1','3'],['1','2'],['1','3'],[]]
function Oracle(name, endpnt) {
this.name = name;
this.endpnt = endpnt
}
var oracles = []
for(var i=0;i<oracleTitle.length;i++) {
// Change this part
oracles.push(new Oracle(oracleTitle[i],oracleEndpnt[i].map(num => parseInt(num))));
}
console.log(oracles)
If I understand correctly this should do:
var oracles = [
{ name: 'oracle1', endpnt: [ '1', '3' ] },
{ name: 'oracle2', endpnt: [ '1', '2' ] },
{ name: 'oracle3', endpnt: [ '1', '3' ] },
{ name: 'oracle4', endpnt: [] }
]
var r = oracles.map(x => {
x.endpnt = x.endpnt.map(z => Number(z))
return x
})
console.log(r)
var oracleTitle= ['oracle1','oracle2','oracle3','oracle4']
var oracleEndpnt = [['1','3'],['1','2'],['1','3'],[]]
function Oracle(name, endpnt) { this.name = name; this.endpnt = endpnt }
var oracles = oracleTitle.map((s, i) => new Oracle(s, oracleEndpnt[i].map(Number)))
console.log( JSON.stringify(oracles) )
I'm trying to form the dictionary from tabs and data by iterating
I'm unable to form dictionary like structure and expected Output is mentioned
const tabs = {
first: 'first',
second: 'second',
third: 'third'
}
const data = {
accounts: {
members: [
{
node: {id: '1', name: 'first'}
},
{
node: {id: '2', name: 'second'}
},
{
node: {id: '3', name: 'third'}
},
]
}
}
let expectedOutput = {'first': '1','second':'2','third':'3'}
We have an object tabs. We can get key from this object using Object.keys(object_name). It will simply return us an array of key.
Object.keys(tabs) => [first, second,third]
data.accounts.members is also an array.We need to use array filter method to extract the node object from data.accounts.members array. Each item in array is an object. We can use object dot notation property to get value.
const filterarray = data.accounts.members.filter(it => it.node.name === tabs[item])[0]
To read first value from array just simply use filterarray[0] index.
Reduce need initial value which is an empty object.We are appending data in this object.
We can simply add data in object using object[key] = value
Here key will be tabs key. tabs is also an object we need to read the value of that key and store result in object result[tabs[item]] = filterarray.node.id
Once reduce is over we will get result.
const tabs = {
first: 'first',
second: 'second',
third: 'third'
}
const data = {
accounts: {
members: [{
node: {
id: '1',
name: 'first'
}
},
{
node: {
id: '2',
name: 'second'
}
},
{
node: {
id: '3',
name: 'third'
}
},
]
}
}
const expectedOut =
Object.keys(tabs).reduce(
(result, item) => {
const ch = data.accounts.members.filter(it => it.node.name === tabs[item])[0]
result[tabs[item]] = ch.node.id
return result
}, {})
console.log(expectedOut)
var values =selectValues;
var names = selectNames;
var priorities = prioritizedHours;
var prefers = preferHrsArray;
var years = workedYearsArray;
var items = values.map((value, index) => {
return {
value: value,
name: names[index],
priority: priorities[index],
prefer: prefers[index],
year: years[index]
}
});
var arrayObject = JSON.stringify(items);
Logger.log('Object array: '+arrayObject);
In the above program, I am creating an object from the arrays such as names, priorities, and so on. Resulting Object is following after I have made a sorting of them:
[
{"value":1,"name":"Fiona","prefer":30,"year":6},
{"value":1,"name":"Martin","prefer":40,"year":7},
{"value":2,"name":"Adam","prefer":0,"year":20},
{"value":2,"name":"Steve","prefer":100,"year":5}
]
Now as sorting is done, I want the arrays back as they are in the Object.
I am trying to get arrays like:
value = [1,1,2,2],
name = ['Fiona', 'Martin','Adam', 'Steve'],
prefer = [30,40,0,100],
year = [6,7,20,5]
Thank you for helping me out.
You can use forEach for this case
const array = [
{"value":1,"name":"Fiona","prefer":30,"year":6},
{"value":1,"name":"Martin","prefer":40,"year":7},
{"value":2,"name":"Adam","prefer":0,"year":20},
{"value":2,"name":"Steve","prefer":100,"year":5}
]
const values = []
const names = []
const prefers = []
const years = []
array.forEach(rec => {
values.push(rec.value),
names.push(rec.name),
prefers.push(rec.prefer),
years.push(rec.year)
})
console.log(values)
console.log(names)
console.log(prefers)
console.log(years)
Map should work:
const data = [
{ value: 1, name: "Fiona", prefer: 30, year: 6 },
{ value: 1, name: "Martin", prefer: 40, year: 7 },
{ value: 2, name: "Adam", prefer: 0, year: 20 },
{ value: 2, name: "Steve", prefer: 100, year: 5 },
];
const values = data.map(x=>x.value);
const names = data.map(x=>x.name);
console.log(values, names);
//[ 1, 1, 2, 2 ] [ 'Fiona', 'Martin', 'Adam', 'Steve' ]
See MDN for details of map
You could also make it a little more dynamic by using reduce and then only getting the lists you want using Object destructuring.
const arr = [
{"value":1,"name":"Fiona","prefer":30,"year":6},
{"value":1,"name":"Martin","prefer":40,"year":7},
{"value":2,"name":"Adam","prefer":0,"year":20},
{"value":2,"name":"Steve","prefer":100,"year":5}
];
const {name, value, prefer, year} = arr.reduce((acc, curr) => {
Object.entries(curr).forEach(([key, val]) => {
if(acc[key] == null)
acc[key] = [];
acc[key].push(val);
});
return acc;
}, {})
console.log(name);
console.log(value);
console.log(prefer);
console.log(year);
I have an Array which contains following data below. I need to filter the list by Array Index number.
The array, does not have array Id number, however, if filterList is [0,2] it should grab the First and Third Element in the array below.
How can this be done?
let filterList = [0,2];
documentPropertyGridData: Array<DocumentPropertyGridData> = new Array<DocumentPropertyGridData>();
let doc1 = new DocumentPropertyGridData();
doc1.documentNumber = '2';
doc1.situsAddress = '123 Oak';
let doc2 = new DocumentPropertyGridData();
doc2.documentNumber = '7';
doc2.situsAddress = '567 3rd Avenue';
let doc3= new DocumentPropertyGridData();
doc3.documentNumber = '9';
doc3.situsAddress = '895 Washington St';
let doc4= new DocumentPropertyGridData();
doc4.documentNumber = '3';
doc34.situsAddress = '894 Forest Road';
this.documentPropertyGridData.push(doc1);
this.documentPropertyGridData.push(doc2);
this.documentPropertyGridData.push(doc3);
this.documentPropertyGridData.push(doc4);
Currently using Typescript in Angular Environment, however JavaScript code will work.
You need to use the filter method of an array to filter based on the index as provided in the filterList.
var arr = [
{
documentNumber: '2',
situsAddress:"123 Oak"
},
{
documentNumber: '7',
situsAddress:"567 3rd Avenue"
},
{
documentNumber: '9',
situsAddress:"895 Washington St"
},
{
documentNumber: '3',
situsAddress:"894 Forest Road"
}
]
var filterList = [0,2];
var result = arr.filter((obj,index) => filterList.includes(index));
console.log(result)
OR
filterList.map((item) => arr[item]))
You could map on filterList to get your documents by index:
var filterList = [0, 2];
var doc = [
{
documentNumber: '2',
situsAddress: "123 Oak"
},
{
documentNumber: '7',
situsAddress: "567 3rd Avenue"
},
{
documentNumber: '9',
situsAddress: "895 Washington St"
},
{
documentNumber: '3',
situsAddress: "894 Forest Road"
}
]
console.log(filterList.map(index => doc[index]))