I'm trying to turn this:
[ { '231634908': 137875 },
{ '388252786': 150004 },
{ '333624027': 144107 },
{ '382758108': 149729 },
{ '384113458': 149803 },
{ '384844004': 149848 },
{ '405877005': 150481 },
{ '405877005': 150481 } ]
Into this:
{
'231634908': 137875,
'388252786': 150004,
'333624027': 144107,
'382758108': 149729,
'384113458': 149803,
'384844004': 149848,
'405877005': 150481,
'405877005': 150481
}
Using underscore.
I tried
_.object(list);
_.object(_.keys(list), _.values(list));
_.object(_.keys(list[0]), _.values(list[0]));
I'm no expert on underscore.js, but try this:
_.extend.apply(null, list);
One caveat: this will actually modify the first element of the list. If this is a concern you might want to use something like this instead:
_.extend.apply(null, [{}].concat(list));
You want _.reduce():
_.reduce(list, function(memo, o) {
var k = Object.keys(o)[0];
memo[k] = o[k];
return memo;
}, {});
A more elegant and native way to do it.
var a = [ { '231634908': 137875 },
{ '388252786': 150004 },
{ '333624027': 144107 },
{ '382758108': 149729 },
{ '384113458': 149803 },
{ '384844004': 149848 },
{ '405877005': 150481 },
{ '405877005': 150481 } ];
var b = {};
Array.prototype.forEach.call(a,function(elem) {
var keys = Object.keys(elem);
b[keys[0]] = elem[keys[0]];
});
One more native solution for case with multiple fields per object
var objects = [ { '231634908': 137875 },
{ '388252786': 150004 },
{ '333624027': 144107 },
{ '382758108': 149729 },
{ '384113458': 149803 },
{ '384844004': 149848 },
{ '405877005': 150481 },
{ '405877005': 150481 } ]
var singleObject = {};
for(var i in objects){
var oKeys = Object.keys(objects[i]);
for(var j in oKeys){
singleObject[oKeys[j]] = objects[i][oKeys[j]];
}
}
console.log(singleObject);
I know this is really old, but it inspired me to do this natively one-line for multi key objects:
var arrayOfObjectsToCombine = [ { foo: 'bar', dog: 'cat' }, { baz: 'boom' } ];
arrayOfObjectsToCombine.reduce(function(done, obj) { Object.keys(obj).map( function(K) { done[K] = obj[K] } ); return done; }, {})
result:
{ foo: 'bar', dog: 'cat', baz: 'boom' }
You could use Object.assign() and spread syntax like this:
let array = [ { '231634908': 137875 },
{ '388252786': 150004 },
{ '333624027': 144107 },
{ '382758108': 149729 },
{ '384113458': 149803 },
{ '384844004': 149848 },
{ '405877005': 150481 },
{ '405877005': 150481 } ]
const output = Object.assign({}, ...array)
console.log(output)
Related
I have an array like this.
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
I want to change it to like this
let me explain it a little. I want to assign the abbreviation directly to the name and the iterate through that array
let outout = [
{
"ISB":"ISLAMABAD"
},
{
"RAW":"ISLAMABAD"
},
{
"SWB":"SWABI"
},
{
"AQ":"AQEEL"
},
]
that is what I tried
let k = arr.map((item) => {
return item.ABB = item.name
})
console.log(k)
and here is the output
[ 'ISLAMABAD', 'PINDI', 'SWABI', 'AQEEL' ]
Here you go, use array map, simples
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
let outout = arr.map(({ABBRIVATION, name}) => ({[ABBRIVATION]: name}));
console.log(outout);
Nothing more than a simple Array.prototype.map() needed.
let arr = [
{
ABBRIVATION: "ISB",
name: "ISLAMABAD",
},
{
ABBRIVATION: "RAW",
name: "PINDI",
},
{
ABBRIVATION: "SWB",
name: "SWABI",
},
{
ABBRIVATION: "AQ",
name: "AQEEL",
},
];
const result = arr.map(e => ({ [e.ABBRIVATION]: e.name }));
console.log(result);
map over the array of objects (map returns a new array) and assign the name to a new key defined by the abbreviation.
You code works the way it does because item.ABB is undefined, but you're also assigning item.name to it which does get returned, so you just get an array of names returned.
const arr=[{ABBRIVATION:"ISB",name:"ISLAMABAD"},{ABBRIVATION:"RAW",name:"PINDI"},{ABBRIVATION:"SWB",name:"SWABI"},{ABBRIVATION:"AQ",name:"AQEEL"}];
const out = arr.map(obj => {
return { [obj.ABBRIVATION]: obj.name };
});
console.log(out);
Hi I have seen people answer, but most of them use the map function, I provide some other solutions, hoping to expand the thinking
Use forEach function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
datas.forEach((obj, i, arr) => {
const{'ABBRIVATION':k, 'name':v} = obj;
arr[i] = {[k]:v};
});
console.log(datas);
Use flatMap function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
const result = datas.flatMap(obj => {
const {'ABBRIVATION':k, 'name':v} = obj;
return {[k]:v};
});
console.log(result);
this is how you suppose to do it.
arr.reduce((d, c)=>([...d, {[c.ABBRIVATION]: c.name}]),[])
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
console.log(arr.reduce((data, current)=>([...data, {[current.ABBRIVATION]: current.name}]),[]))
I have two arrays below.
array 1:
{
"0":{
"countries":{
"BDI":{
"count":1
},
"IRN":{
"count":1
}
},
"checkId":"16835659691517226105"
},
"1":{
"countries":{
"ZAF":{
"count":2
}
},
"checkId":"144165083478491226"
}
}
array2:
{
"0":{
"countries":{
"AIA":{
"count":2
}
},
"checkId":"144165083478491106"
},
"1":{
"countries":{
"BDI":{
"count":1
},
"IRN":{
"count":1
},
"ATA":{
"count":5
}
},
"checkId":"16835659691517226105"
}
}
I want to find the mismatch and common element between the two arrays. currently, I am executing two for loops to find the matching element between two array-based on checkids but I am not able to find the non-common elements from these two.
some code snippets
array1.forEach(each => {
array2.forEach(compareTask => {
var teastEach = Object.entries(compareTask.countries);
if (each.checkId === compareTask.checkId) {
firstCount = each.count
secondCount = compareTask.count
countDifference = secondCount - firstCount
......
I am able to get the common checkids but not getting the non-common checkids.
expected output:
{
"0":{
"countries":{
"ZAF":{
"count":2
}
},
"checkId":"144165083478491226"
},
"1":{
"countries":{
"AIA":{
"count":2
}
},
"checkId":"144165083478491106"
}
}
From the comments it looks like you could use Map()
object1 = { "0": { countries: { BDI: { count: 1, }, IRN: { count: 1, }, }, checkId: "16835659691517226105", }, "1": { countries: { ZAF: { count: 2, }, }, checkId: "144165083478491226", }, };
object2 = { "0": { countries: { AIA: { count: 2, }, }, checkId: "144165083478491106", }, "1": { countries: { BDI: { count: 1, }, IRN: { count: 1, }, ATA: { count: 5, }, }, checkId: "16835659691517226105", }, };
map = new Map();
arr = [Object.values(object1), Object.values(object2)].flat();
result = [
...arr
.reduce((r, o) => {
const dupli = r.get(o.checkId);
dupli ? r.delete(o.checkId) : r.set(o.checkId, o);
return r;
}, new Map())
.values(),
];
console.log(result);
I have a json array with different key values and need to add a ServerUrl to the beginning of all node values using a loop without writing multiple statements to do that by using javascript:
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
The expected result must be:
"Urls": [
{ "getCar": "http://192.168.1.1:3000/getAllCars" },
{ "getPerson": "http://192.168.1.1:3000/getAllPersons" },
{ "getBook": "http://192.168.1.1:3000/getAllBooks" }
],
Any advice would be appreciated.
You can use map to map your objects to new objects. Those objects have a single property, which you can get with Object.keys. The new object can get that same property name using the computed property name feature:
var obj = {
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
};
var urls = obj.Urls.map(o => Object.keys(o).map(k => ({ [k]: obj.ServerUrl + o[k] }))[0]);
console.log(urls);
const jsonVal = {
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
}
const result = jsonVal.Urls.map(val =>
Object.keys(val).reduce((resultObj, endpointKey) => {
resultObj[endpointKey] = `${jsonVal.ServerUrl}${val[endpointKey]}`;
return resultObj;
}, {})
);
Try (where your data are in d)
d.Urls.forEach( (x,i,a,k=Object.keys(x)[0]) => x[k] = d.ServerUrl + x[k]);
let d = {
"Urls": [
{ "getCar": "/GetAllGroupCustomers" },
{ "getPerson": "/getAllItems" },
{ "getBook": "/GetAllCustomers" }
],
"ServerUrl": "http://192.168.1.1:3000"
}
d.Urls.forEach( (x,i,a,k=Object.keys(x)[0]) => x[k] = d.ServerUrl + x[k]);
console.log(d);
A version that modifies your own object
var obj = {
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
};
obj.Urls.forEach(o => o[Object.keys(o)[0]] = `${obj.ServerUrl}${o[Object.keys(o)[0]]}`);
console.log(obj);
It should be returning 9-12,1-4,5-8,9-11 but instead it's returning 9-12,1-4,5-8,9-11,,,,
var arr = [{
Sanju: '9-12'
}, {
Sanju: '1-4'
}, {
Sanju: '5-8'
}, {
Sanju: '9-11'
},
{
IRONMAN: '9-12'
}, {
VIVEGAM: '1-4'
}, {
VIVEGAM: '5-8'
}, {
VIVEGAM: '9-11'
}
];
var b = Array.from(arr, x => x.Sanju);
document.write(b);
document.write(Array.isArray(b));
Since not all values in arr contains Sanju, some of the values will give you undefined when you return x.Sanju You can use filter to remove those like
var arr = [{Sanju: '9-12'},{Sanju: '1-4'}, {Sanju: '5-8'},{Sanju: '9-11'},
{IRONMAN: '9-12'},{VIVEGAM: '1-4'}, {VIVEGAM: '5-8'},{VIVEGAM: '9-11'}
];
var b= Array.from(arr, x => x.Sanju).filter(Boolean);
document.write(b);
document.write(Array.isArray(b));
Check Removing undefined values from Array for more details on how .filter(Boolean) works
It should be returning 9-12,1-4,5-8,9-11 but instead it's returning 9-12,1-4,5-8,9-11,,,,
Coz there is no Sanju property on some of the objects. You should first filter you array and then do the rest
var arr = [{
Sanju: '9-12'
}, {
Sanju: '1-4'
}, {
Sanju: '5-8'
}, {
Sanju: '9-11'
},
{
IRONMAN: '9-12'
}, {
VIVEGAM: '1-4'
}, {
VIVEGAM: '5-8'
}, {
VIVEGAM: '9-11'
}
];
var o = arr.filter(i=> i.Sanju);
var b = Array.from(o, x => x.Sanju);
document.write(b);
document.write(Array.isArray(b));
Do I need to execute a bind(this) somewhere and the console log placement seems to be off?
var company = {
employees: [{
name: "doug"
},
{
name: "AJ"
}
],
getName: function(employee) {
return employee.name
},
getNames: function() {
return this.employees.map(this.getName)
},
delayedGetNames: function() {
setTimeout(this.getNames, 500)
}
}
console.log(company.delayedGetNames());
setTimeout(this.getNames.bind(this), 500)
^
|
+----< HERE
var company = {
employees: [{
name: "doug"
},
{
name: "AJ"
}
],
getName: function(employee) {
return employee.name
},
getNames: function() {
return this.employees.map(this.getName)
},
delayedGetNames: function() {
var fn = function() {
var names = this.getNames();
console.log(names);
};
setTimeout(fn.bind(this), 500);
}
}
company.delayedGetNames();