I have an array like that
I want to pick the array item by property name, I am using lodash for that:
const result = _.map(this.thing, _.property('groups')).filter(x => x !== undefined);
But I am getting array of arrays as result
What I need is just single selected property array.
Any idea how to achieve that?
Try this>>>
var a = [{"p1":[3,4]},{"p2":[6,7]}];
function getArr(arr,key){
var res = [];
for(var v of arr){
if(v[key]!=undefined){
res = v[key];break;
}
};
return res;
}
console.log(getArr(a,"p1"));
If you can use ES6/ES7, you can rely on Object.keys and Object.values to access to the key (that is the property name) and the value (the array you want to get):
var arr = [
{ groups: [1, 2 ] },
{ category: [1, 2, 3 ] },
{ subCategory: [1, 2, 3, 4 ] }
];
function pickArray(propertyName) {
var element = arr.find(el => Object.keys(el)[0] === propertyName)
return element ? Object.values(element)[0] : null;
}
var res = pickArray('category');
console.log(res);
const output
= (Array.from(arr, (obj) => obj['product'], 'product')
.filter(x => typeof x !== 'undefined'))[0];
Try this:
const arr = [ {'groups': ['item1','item2']},
{'categories':['x','y']}
]
var ouptut= arr.find(item=> {
return item[Object.keys(item).find(key=>key === 'groups')]
})
console.log(ouptut)
Related
i´m struggling with a Array in a Object stored in a Array with Objects from which I want return all Indicies.
Function to generate Object looks like this:
const addArray = function(a, b) {
const object = {
name: a,
rooms: b
};
testArray.push(object);
};
What I want to achieve is to cycle through the "testArray" and return every Index from the Object where the Array Rooms contains "Office" for example.
I´ve already tried to use a function like this but I don´t seem to be able to get the right Syntax for the Array in the Object:
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.rooms.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
};
Thanks in advance!
Edit:
Additional Informations to Data:
A Object with data filled would look like this:
const device = {
name: "TV",
rooms: ["Living Room", "Bedroom"]
};
After generating Objects like this I push them to an array witch only contains this objects (see function addArray)
You can use Array.flatMap() to map each value of the array at matches val to it's index, and the rest to empty array, which will be removed by the flatMap:
const getAllIndexes =(arr, val) => arr.flatMap((v, i) => v === val ? i : [])
const arr = [1, 2, 3, 1, 2, 1, 1, 2]
const result = getAllIndexes(arr, 1)
console.log(result)
Using your array of objects, you'll need to compare a value, or check if an object meets some condition. It's better in this case to replace val with a predicate function:
const getAllIndexes =(arr, pred) => arr.flatMap((v, i) => pred(v) ? i : [])
const arr = [{ rooms: [1, 2, 3] }, { rooms: [2, 1, 1] }, { rooms: [3, 2, 2] }, { rooms: [1, 2, 1] }]
const result = getAllIndexes(arr, o => o.rooms.includes(1))
console.log(result)
Try using Array.prototype.map and Array.prototype.filter
function getAllIndexes(arr, val) {
return arr.map(i=> {
let room = i.rooms;
return room.indexOf(val);
}).filter(a=>{
a != -1;
});
};
You could destructure rooms from the device and get the index, if the wanted value is found.
const
room = 'Office',
indices = array.flatMap(({ rooms }, i) => rooms.includes(room) ? i : []);
The above code features a former solution from me with hacking Array#flatMap.
My below code is working fine and gives the correct desired output. But I am trying to use map, filter etc. instead of for loop. Lodash map and filter also works.
var arr = [
{"comp_id":1, desc: 'from comp1', updated: true},
{
"comp_id":2, desc: 'from comp2', updated: false}
];
var complaint_sources = [
{"comp_id":2,"consumer_source":"Hotline In","description_option":"English"},
{"comp_id":1,"consumer_source":"Online","description_option":"Other"},
{"comp_id":1,"consumer_source":"Email","description_option":null},
{"comp_id":2,"consumer_source":"Email","description_option":null}]
for(let i =0 ;i<arr.length;i++) {
let x=[];
for(let j=0;j<complaint_sources.length;j++){
if(arr[i].comp_id === complaint_sources[j].comp_id){
x.push(complaint_sources[j]);
arr[i].comp_src = x;
}
}
}
console.log(arr);
Basically I am looping through arr array and inside that looping through the complaint_sources array and when the comp_id matches I am modifying the arr array and adding a comp_src property to the object of arr array. This comp_src property will be an array of complaint_sources matched by comp_id.
this will work:
var arr = [
{"comp_id":1, desc: 'from comp1', updated: true},
{"comp_id":2, desc: 'from comp2', updated: false}
];
var complaint_sources = [
{"comp_id":2,"consumer_source":"Hotline In","description_option":"English"},
{"comp_id":1,"consumer_source":"Online","description_option":"Other"},
{"comp_id":1,"consumer_source":"Email","description_option":null},
{"comp_id":2,"consumer_source":"Email","description_option":null}
];
const grouped_sources = complaint_sources.reduce((acc, value) => {
(acc[value.comp_id] = acc[value.comp_id] || []).push(value);
return acc;
}, {})
const data = arr.map((comp) => ({
...comp,
comp_src: grouped_sources[comp.comp_id]
}));
console.log(data);
I got problem, I've array of string as
[
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
I need to convert it to Object
[
{"Time" : "25/10/2019 14:49:47.41", "Server", "Daniel.Europe..", .. },
{}
]
likewise.
JSON.parse won't work on non-serialized string.
Using Object.fromEntries()
var data = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
var result = data.map(v =>
Object.fromEntries(v.split(',').map(v => v.split(/:(.*)/)))
)
console.log(result)
Something like this should work:
input.map(v => v.split(',').map(v => {
const [key, ...value] = v.split(':');
const obj = {};
obj[key] = value.join(':');
return obj;
}))
You can get it using map and reduce:
const arr = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
const newArr = arr.map(item => {
return item.split(",").reduce((acc, curr) => {
const label = curr.split(":")[0];
const value = curr.substring(label.length+1)
acc[curr.split(":")[0]] = value
return acc;
},{})
})
console.log(newArr)
You have to split your strings by commas and colons. Only problem is that your time string has a bunch of colons in it. Here is a start.
var a = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
];
b = a.map(function(line) {
var obj = {};
line.split(",").forEach(function(item) {
kv = item.split(/:(.+)/,2);
obj[kv[0]]=kv[1];
});
return obj;
});
console.log(b);
I am working on react project. I have an array which is not a state variable but a constant. The array contains undefined values as its element. I want to make undefined values as empty array. The array finally should contain values without undefined values. Can anyone help to solve this issue?
if array is [undefined, 1,2,[] ], i need to convert it to [[], 1,2,[] ]
array.forEach(dataSet =>
(dataSet.dataPoint = (dataSet.dataPoint === undefined) ? [] : dataSet.dataPoint)
);
you can map your array into another array:
const array2 = array1.map(item => {
return typeof item === 'undefined'
? []
: item
})
https://codepen.io/giannidk/pen/PoYQvBM?editors=0011
1) Use map as you are trying to return array as forEach just iterates over the array.
const array = [undefined, 1,2,[] ]
let newArr = array.map((dataSet) => {
return dataSet = (dataSet === undefined) ? [] : dataSet
})
console.log(newArr) // [[], 1, 2,[]]
You could map over the array and return the value of what you'd like in the new array:
array = array.map(dataSet =>
(dataSet.dataPoint = (dataSet.dataPoint === undefined) ? [] : dataSet.dataPoint)
);
let array = [{}, { dataPoint: 1 }, {}, { dataPoint: 2 }];
array = array.map(dataSet =>
(dataSet.dataPoint = (dataSet.dataPoint === undefined) ? [] : dataSet.dataPoint)
);
console.log(array)
An approach to mutate the original array (rather than reassign / create a new array):
const array = [{}, {
dataPoint: 1
}, {}, {
dataPoint: 2
}];
array.forEach((dataSet, index) => {
array[index] = dataSet.dataPoint === undefined ? [] : dataSet.dataPoint
});
console.log(array)
How to replace array of object with another array of object base on property?
var arr = [
{'status':'ok'},
{'status':'ok'},
{'status':'error'}
]
var arr2 = [
{'status':error, 'msg': 'etc', 'more property':true}
]
arr = arr.forEach((obj,i) => { if(obj.status === 'error'){obj = arr2[i]} return obj })
My above code failed, status ok is gone, I wonder what is wrong.
You can do it using Array#map() to create a new array and Array#find() to find the object in the second array
let arr=[{status:"ok"},{status:"ok"},{status:"error"}],
arr2=[{status:"error",msg:"etc","more property":!0}];
arr = arr.map(a=>{
let fullObj = arr2.find(a2=>a2.status===a.status);
return fullObj ? fullObj : a;
});
console.log(arr);
You could use Object.assign for assigning new properties to a given object.
var arr = [{ status: 'ok' }, { status: 'ok' }, { status: 'error' }],
arr2 = [{ status: 'error', msg: 'etc', 'more property': true }];
arr.forEach(obj => {
if (obj.status === 'error') {
Object.assign(obj, arr2[0]);
}
});
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var arr = [
{'status':'ok'},
{'status':'ok'},
{'status':'error'}
]
var arr2 = [
{'status':error, 'msg': 'etc', 'more property':true}
]
arr = arr.forEach(obj => { if(obj.status === 'error'){obj = arr2[i]} return obj })
The callback in forEach() can take an additional arg for the index, but you forgot to provide it. So if you're trying to access the index you can do that.
Also, you're assigning arr to the output of forEach, but forEach() does not return anything, it just executes a callback for every element in the array. What you can do is swap it out for map, which is similar, but actually returns a new array.
Ex:
arr = arr.map((obj, i) => obj.status === 'error' ? arr2[i] : obj)
I think what you're trying to do is replace the one with status "error" to be the arr2 object [0] so..
for(obj in arr){
arr[obj] = arr[obj]['status'] == 'error' ? arr2[0] : arr[obj];
}