I need your help:
I have an Array (data) containing objects:
var data = [
0: Object { hex: "#ff847f", length: "20" }
1: Object { hex: "#afff90", length: "18" }
2: Object { hex: "#afff90", length: "40" }
3: Object { hex: "#6d91b0", length: "30" }
4: Object { hex: "#ff847f", length: "20" }
]
I need a function, that results me an new Array, which has only unique hex-values AND add up the length-values of the equal hex-values.
The result should look like this:
var data2 = [
0: Object { hex: "#ff847f", length: "40" }
1: Object { hex: "#afff90", length: "58" }
2: Object { hex: "#6d91b0", length: "30" }
]
Thanks for ur ideas.
This is probably not the best solution, but it works. The challenging bit is the fact that you want your length as a string instead of a number. Here is my solution, I hope it helps!
const transformArray = (arr) => {
//first you need to convert the lengths to numbers to make adding easier
arr.map((item) => {
item.length = Number(item.length)
})
//then combine like objects
let output = [];
arr.forEach((dataObj) => {
let found=false;
for (let i=0; i<output.length; i++) {
if (output[i].hex === dataObj.hex) {
output[i].length+= dataObj.length;
found=true;
}
}
if (found===false) {
output.push(dataObj)
}
});
//then convert your lengths back to strings
arr.map((item) => {
item.length = item.length.toString();
})
return output;
}
Related
i have this object array:
let arr = [
{
'pippo': '1',
'descrizione': 'ciao'
}
];
and i want convert "1" to 1 by key:
let arr = [
{
'pippo': 1,
'descrizione': 'ciao'
}
];
any solution?
br
Max
You can iterate over the objects and create a new array with the converted number with the help of parseInt().
arr = arr.map(item => {
return {
...item, //copies all items first...
pippo: parseInt(item.pippo) //...then overwrites pippo
}
}
I am having what I think is a pretty trivial problem but somehow I can't find a solution to. I have a response body that looks like this:
{
"sizes": [
{
"43": 35
},
{
"42": 20
},
{
"38": 10
}
]
}
where the keys are shoe sizes and the value is quantity of each size. How do I access the sizes? What I currently have is this:
const sizesArray = response.data.sizes
const arr = Object.values(msizes);
console.log('arr', arr);
arr.map((i,a) => {
console.log('i',i);
console.log('a',a);
})
but i is then again a object {43: 35}
and a is just the index. I want somehow to assign the key to parameter called 'sizes' and the key to a parameter called quantity.
You can use Object.keys, a bit simpler than Object.entries
Example:
const data = { sizes: [{ "43": 35 }, { "42": 20 }, { "38": 10 }] };
const result = data.sizes.map((element, index) => {
let obj = Object.keys(element); // returns an array of keys
let key = obj[0]; // first element is the only key
let quantity = element[key]; // bracket notation, key is an string, not number
console.log("size", key);
console.log("quantity", quantity);
});
You can just iterate the sizes array, using reduce to append the keys of each object to an output array of sizes:
const data = { sizes: [{ "43": 35 }, { "42": 20 }, { "38": 10 }] }
const sizes = data.sizes.reduce((acc, s) => acc.concat(Object.keys(s)), [])
console.log(sizes)
If you want sizes and quantities, you can take a similar approach, just generate an object which accumulates both sets of values:
const data = { sizes: [{ "43": 35 }, { "42": 20 }, { "38": 10 }] }
const { sizes, quantities } = data.sizes
.reduce((acc, s) => {
acc.sizes = acc.sizes.concat(Object.keys(s))
acc.quantities = acc.quantities.concat(Object.values(s))
return acc
},
{ sizes : [], quantities : [] })
console.log(sizes)
console.log(quantities)
You were on the right track :)
Use Object.keys() to get an array of your keys (shoe-sizes). Then use the map()-function to create a new array. Use the index of map() to access the quantity in your response.
const sizesArray = response.data.sizes
const sizes = Object.keys(sizesArray);
const result = sizes.map((element, index) => ({
size: element,
quantity: sizesArray[index]
}));
console.log(result);
I have 2 arrays of objects below. I want to compare both and check the matched random_code and get the score
based on the matched random code. I have provided the sample result below. Thanks
me.records.data1(array of objects)
[
{
id: 345,
user: 223,
random_code: "50-3910111611011",
created_at: "2019-03-01",
is_verified: false,
…
} 1:{
id: 346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
is_verified:false,
…
}
]
me.records.data2(array of objects)
[
{
id:161,
questionaire_content:80,
questionaire_content_choice:272,
created_at:"2019-03-01",
random_code:"50-3910111611011",
score:"0",
…
} 1:{
id:162,
questionaire_content:79,
questionaire_content_choice:270,
created_at:"2019-03-01",
random_code:"50-101966854102",
score:"1",
…
}
]
result should be like this based on the data above.
]{
id:345,
user:223,
random_code:"50-3910111611011",
created_at:"2019-03-01",
score:0,
is_verified:false,
…
}{
id:346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
score:1,
is_verified:false,
…
}
]
What you need to do is:
Iterate over the source array.
For each item in the source array, get the “random_code” key for the object, and store the value in a temporary variable.
From the scores array, find an object whose “random_code” matches the one stored in the temporary variable, if found, return the “score” key’s value.
const source = [
{
id: 345,
user: 223,
random_code: "50-3910111611011",
created_at: "2019-03-01",
is_verified: false,
}, {
id: 346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
is_verified:false,
}
];
const scores = [
{
id:161,
questionaire_content:80,
questionaire_content_choice:272,
created_at:"2019-03-01",
random_code:"50-3910111611011",
score:"0",
}, {
id:162,
questionaire_content:79,
questionaire_content_choice:270,
created_at:"2019-03-01",
random_code:"50-101966854102",
score:"1",
}
];
// function to get the value of score key from scores array for matching random code.
const getScoreForRandomCode = (randomCode) => {
for (let index = 0; index < scores.length; index++) {
const tempScore = scores[index];
if (tempScore.random_code === randomCode) {
return tempScore.score;
}
}
}
const result = source.map ((item) => {
const randomCode = item.random_code;
const score = getScoreForRandomCode (randomCode);
return {
...item,
score: score || 'NA'
};
});
console.log (result);
Use forEach to loop through the me.records.data1, and match the random_code within me.records.data2. When the random_code matched, will assign the data2.score to me.records.data1.
me.records.data1.forEach(function(obj){
var bscore = "";
data2 = me.records.data2.find(function(i) { if(i.random_code === obj.random_code) return i.score; });
if(bscore!="") obj.score = data2.score;
});
Following is my code to get the languages with Language id and language text
for (var p in $scope.bulk.Langugaes) {
$scope.lsLanguagewithTextndValue.push($scope.bulk.Langugaes[p].Value, $scope.bulk.Langugaes[p].Text);
}
but for above code the value in lsLanguagewithTextndValue
0:"1"
1:"Marathi"
2:"2"
3:"English"
4:"4"
5:"Hindi"
6:"3"
7:"French"
But I want output like this
1:Marathi
2:English
3.Hindi
4.French
$scope.lsLanguagewithTextndValue.push({ $scope.bulk.Langugaes[p].Value: $scope.bulk.Langugaes[p].Text });
Multiple arguments in .push just pushes each argument in to the array.
If you want to add a pair key - value do it like this:
obj[key] = value;
In your case it should be something like this:
for (var p in $scope.bulk.Langugaes) {
$scope.lsLanguagewithTextndValue[$scope.bulk.Langugaes[p].Value] = $scope.bulk.Langugaes[p].Text;
}
Try this.
const $scope = {
bulk: {
Languages: {
ln1: { value: 1, text: 'Marathi' },
ln2: { value: 2, text: 'English' },
ln3: { value: 3, text: 'Hindi' },
ln4: { value: 4, text: 'French' }
}
},
lsLanguagewithTextndValue: []
}
// just to make it more readable
const langs = $scope.bulk.Languages;
for (let p in langs) {
$scope.lsLanguagewithTextndValue.push({[langs[p].value]: langs[p].text})
}
console.log($scope.lsLanguagewithTextndValue);
In this case use map Array map. This function make a new array with elements of another.
$scope.lsLanguagewithTextndValue =
$scope.bulk.Langugaes.map((langugaes) => {
// langugaes its a element of $scope.bulk.Langugaes for example
// $scope.bulk.Langugaes[p]
return {langugaes.Value: langugaes.Text}
})
Result:
{
"1": "Marathi"
},
{
"2": "English"
},
{
"3": "Hindi"
},
{
"4": "French"
}
For instance the array:
var arr = [
{
Test 0: 142.0465973851827,
Test 1: 199,
timestamp: "2017-01-16T00:00:00.000Z"
},
{
Test 0: 142.0465973851827,
Test 1: 199,
timestamp: "2017-01-17T00:00:00.000Z"
}
]
Test 0 and Test 1 can be anything. and I try to return such result:
var arr = [
{
total: 341,
timestamp: '2017-01-16T00:00:00.000Z'
},
{
total: 341,
timestamp: '2017-01-17T00:00:00.000'
}
]
What would be the proper loop type to do it?
You can map over the array, then run reduce on the Object.keys of each object, excluding the timestamp property
var arr = [{
Test0: 142.0465973851827,
Test1: 199,
timestamp: "2017-01-16T00:00:00.000Z"
}, {
Test0: 142.0465973851827,
Test1: 199,
timestamp: "2017-01-17T00:00:00.000Z"
}]
var res = arr.map(v => ({
total: Object.keys(v).reduce((a, b) => b !== 'timestamp' ? a + v[b] : a, 0),
timestamp: v.timestamp
}));
console.log(res);
A combination of array.map, Object.keys, array.filter, and array.reduce can do this. Use array.map to run through the array, Object.keys to get the keys of each object and array.filter to only grab the keys starting with "Test", then accumulate results using array.reduce.
All of the above can easily be done using simple loops as well. The array methods can be done using a regular for loop, while Object.keys will need a for-in guarded with object.hasOwnProperty.
like this?
function number(v){ return +v || 0; }
arr.map(function(obj){
var timestamp = obj.timestamp;
var total = Object.keys(obj)
.reduce(function(sum, key){
return sum + number( obj[key] );
}, 0);
return { total, timestamp }
})
What about this?
var arr = [
{
Test0: 142.0465973851827,
Test1: 199,
timestamp: "2017-01-16T00:00:00.000Z"
},
{
Test0: 142.0465973851827,
Test1: 199,
timestamp: "2017-01-17T00:00:00.000Z"
}
];
var result = [];
var exclude = "timestamp";
arr.forEach(function(elements){
var sum = 0;
for(key in elements){
if(key !== exclude){
sum += elements[key];
}
}
var newElement = {total: sum.toFixed(2), timestamp: elements.timestamp}
result.push(newElement);
});
console.info(result);
arr=arr.map(el=>{return el.total=Object.keys(el).filter(key=>key.split("Test")[1]).reduce((total,key)=>total+el[key],0),el;});
it does exactly what joseph the dreamer described in the first part of his answer.