I have a question here I want to get all the value of the values array inside this array.
const sample = [
{
"key": "sampleKey", "values":
[
{ "key": "insidesampleKey", "value": 2 },
{ "key": "insideofinside", "value": 2 }
]
},
{
"key": "sampleKey2", "values":
[
{ "key": "insideSampleKey2", "value": 1 }
]
},
{
"key": "samplkey3", "values":
[
{ "key": "insideofsampleKey3", "value": 1 }
]
}
]
So far, I can only print the first one console.log(sample[0].values[0].value). I appreciate with any helps. Thanks much and have a great weekend
I think flatMap may be the best way to deal with this.
sample.flatMap(outer => outer.values.map(inner => inner.value))
You can use reduce and concat to get a flat, single array.
const sample = [{"key":"sampleKey","values":
[{"key":"insidesampleKey","value":2},{"key":"insideofinside","value":2}]},
{"key":"sampleKey2","values":[{"key":"insideSampleKey2","value":1}]},
{"key":"samplkey3","values":[{"key":"insideofsampleKey3","value":1}]}]
var values = sample.reduce((acc, item) => acc.concat(item.values.map(v=> v.value)),[]);
console.log(values);
The easiest method is to use a flatMap over the array as below. You can use polyfill for browsers that don't support the same yet. Use MDN to learn more.
sample.flatMap(item => item.values.map(inner => inner.value))
If you want to print the other value properties, just map over the array, then look at the values array, then look at value, and finally use flat to get a single array:
const sample = [{
"key": "sampleKey",
"values": [{
"key": "insidesampleKey",
"value": 2
}, {
"key": "insideofinside",
"value": 2
}]
},
{
"key": "sampleKey2",
"values": [{
"key": "insideSampleKey2",
"value": 1
}]
},
{
"key": "samplkey3",
"values": [{
"key": "insideofsampleKey3",
"value": 1
}]
}
];
console.log(sample.map(e => e.values.map(x => x.value)).flat(1));
Related
In my case i have a 2 db queries which are objects, one which returns all possible items which consists of a key and name field and then the other is a object which has the key, name and value field. What i am trying to do is to merge both objects where object 1 is the main object and object 2 should be merged into it.
What i ideally want is to return all items in Data2 with the value field merged into data2 and 0 if there is no data in data 1. if thats not possible i would be ok with no value in items in data 2 but i get even a strange result for that.
Fyi i am using underscore
const data1 = [
{
"count": 2,
"key": "c28f7ead-d87b-4ad5-b6b3-1f204b013b50",
"name": "Notes Written"
},
{
"count": 1,
"key": "d0181c74-22a9-4f99-9cc9-df3467c51805",
"name": "Pop-Bys Delivered"
},
{
"count": 2,
"key": "90d142ea-6748-4781-b2b9-4f05aab12956",
"name": "Database Additions"
},
{
"count": 1,
"key": "723e95dd-8c47-48ed-b9c3-1b010b092a1b",
"name": "Referals Given"
}
]
const data2 = [
{
"key": "8646ec5d-7a72-49bd-9a68-cf326d1c4a14",
"name": "Calls Made"
},
{
"key": "c28f7ead-d87b-4ad5-b6b3-1f204b013b50",
"name": "Notes Written"
},
{
"key": "d0181c74-22a9-4f99-9cc9-df3467c51805",
"name": "Pop-Bys Delivered"
},
{
"key": "90d142ea-6748-4781-b2b9-4f05aab12956",
"name": "Database Additions"
},
{
"key": "723e95dd-8c47-48ed-b9c3-1b010b092a1b",
"name": "Referals Given"
},
{
"key": "0f054686-ef13-4993-ac5b-f640ceeaaa8d",
"name": "Referals Received"
}
]
console.log(_.extend( data2, data1 ))
Here is a Replit example Sample Code
Using reduce, iterate over data1 while updating a Map of key-count pairs
Using each, iterate over data2 and set the value to the value of the key from the map, or 0 if it doesn't exist
const
data1 = [ { "count": 2, "key": "c28f7ead-d87b-4ad5-b6b3-1f204b013b50", "name": "Notes Written" }, { "count": 1, "key": "d0181c74-22a9-4f99-9cc9-df3467c51805", "name": "Pop-Bys Delivered" }, { "count": 2, "key": "90d142ea-6748-4781-b2b9-4f05aab12956", "name": "Database Additions" }, { "count": 1, "key": "723e95dd-8c47-48ed-b9c3-1b010b092a1b", "name": "Referals Given" } ],
data2 = [ { "key": "8646ec5d-7a72-49bd-9a68-cf326d1c4a14", "name": "Calls Made" }, { "key": "c28f7ead-d87b-4ad5-b6b3-1f204b013b50", "name": "Notes Written" }, { "key": "d0181c74-22a9-4f99-9cc9-df3467c51805", "name": "Pop-Bys Delivered" }, { "key": "90d142ea-6748-4781-b2b9-4f05aab12956", "name": "Database Additions" }, { "key": "723e95dd-8c47-48ed-b9c3-1b010b092a1b", "name": "Referals Given" }, { "key": "0f054686-ef13-4993-ac5b-f640ceeaaa8d", "name": "Referals Received" } ];
const map = _.reduce(
data1,
(map, { key, count }) => map.set(key, count),
new Map
);
_.each(
data2,
e => e.value = map.get(e.key) || 0
);
console.log(data2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js" integrity="sha512-ZuOjyqq409+q6uc49UiBF3fTeyRyP8Qs0Jf/7FxH5LfhqBMzrR5cwbpDA4BgzSo884w6q/+oNdIeHenOqhISGw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
I am trying to achieve a data structure in javascript that looks like this:
settings: {
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
}
The amount of keys is variable and needs to be iterated over. I thought I could do it with an array but the [0] numbers are getting in the way.
This is what i have now:
convertSettingsToApiSaveFormat(values) {
const keys = Object.keys(values);
const items = Object.values(values);
const valuesToSend = keys.map((key, i) => {
return { key, value: items[i] };
});
return { settings: [valuesToSend] };
}
}
Which returns:
any help is much appreciated!
First of all this is an invalid data structure
settings: {
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
}
JavaScript object is bascally key value pair you can see the bellow two objects dont have and key.
Either it can be like this
settings: {
"someKey": { "key": "Language", "value": "en" },
"someKey2": { "key": "Language", "value": "en" }
}
or a simple JS array
settings: [
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
]
You're placing valuesToSend inside an array - remove it, and you'll get your desired output*:
return { settings: valuesToSend };
* The result you currently want is invalid - this, however, is valid:
settings: [
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
}
Consider expectedData is the subset array I would like to check inside actualData array.
I tried the following but it fails on first error. I would like to have all the differences between actual and expected arrays listed at the end of execution with an assertion failure.
expectedData.forEach((item) => {
assert.deepInclude(actualData, item, 'actual data did not include item')
})
Example Data:
let expectedData = [
{
"val": -10.12,
"key": "ABC"
},
{
"val": 10.12,
"key": "DEF"
},
]
let actualData = [
{
"val": -10.12,
"key": "ABC"
},
{
"val": 10.12,
"key": "DEF"
},
{
"val": 9.8,
"key": "LMN"
},
]
I'm not sure why I missed this when I first looked, but the code you posted has a (many?) syntax error(s). Try this:
let expectedData = [
{
"val": -10.1,
"key": "ABC"
},
{
"val": 10.12,
"key": "DE"
},
{
"val": 9.8,
"key": "LMN"
},
]
let actualData = [
{
"val": -10.12,
"key": "ABC"
},
{
"val": 10.12,
"key": "DEF"
},
{
"val": 9.8,
"key": "LMN"
},
{
"val": 1,
"key": "XYZ"
},
]
expectedData.forEach((item) => {
assert.deepInclude(actualData, item, 'actual data did not include item')
})
Couldn't find any built in method. For now, Used For loops to iterate through each element to compare and saved the mismatches to an output array.
I have an array like this one :
[
Object {
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
Object {
"hex": "#50690e",
"label": "text",
"value": "354",
},
Object {
"hex": "#925fa3",
"label": "text",
"value": "355"
}]
I have another array with this :
Array [
"355",
"356"
]
I'm looking to create a the first array but without the objects containing value 355 and 356. I tried with .filter()... but I'm a newbie with JS & React Native :-)
I tried some stuffs but almost every time I recreate my Array only with the values (i'm losing the objects inside)...
What I want to do is :
If I found 355 and 356 in my First Array, I delete the objects with them and I recreate my array with the only object remaining (value 364)
I was thinking about sth like that :
myFirstArray.filter(item => item.value != mySecondArray.value) but it's not a success ...
Thanks for help
The previous answers involve iterating over your id's array many times.
A more performant solution would be to store the id's in a set and then use that combined with a filter to produce your new array.
const arr = [
{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
...,
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}];
const ids = ["354", "355"];
const idSet = new Set(ids);
const output = arr.filter(e => !idSet.has(e.value));
var firstArray = [{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
{
"hex": "#50690e",
"label": "text",
"value": "354",
},
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}]
var secondArray = [
"355",
"356"
]
var thirdArray = firstArray.filter(item => secondArray.includes(item.value))
console.log(thirdArray)
You are nearly there, just use Array#includes() to determine whether or not the value of an item is in the second array:
myFirstArray.filter(item => !mySecondArray.includes(item.value))
let myFirstArray = [{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
{
"hex": "#50690e",
"label": "text",
"value": "354",
},
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}
]
let mySecondArray = [
"355",
"356"
]
console.log(
myFirstArray.filter(item => !mySecondArray.includes(item.value))
)
I need your help to understand how to sort array of objects with another array inside each of object. I have response from api with array bunch of objects like below:
[
{
"name": "[C US Equity] CITIGROUP INC",
"stats": [
{
"label": "DTD",
"value": null
},
{
"label": "MTD",
"value": null
},
{
"label": "YTD",
"value": 0.0536530913792681
},
{
"label": 2016,
"value": 0.18102519526139493
},
{
"label": 2015,
"value": -0.012946569977188238
},
{
"label": 2014,
"value": null
}
]
}...
]
I should be sort it by value of label "YTD" exclude of null value. Any help are welcome
You can use array#sort method
var oldArray = [{
"name": "[C US Equity] CITIGROUP INC",
"stats": [{
"label": "DTD",
"value": null
},
{
"label": "MTD",
"value": null
},
{
"label": "YTD",
"value": 0.0536530913792681
},
{
"label": 2016,
"value": 0.18102519526139493
},
{
"label": 2015,
"value": -0.012946569977188238
},
{
"label": 2014,
"value": null
}
]
}];
oldArray[0].stats.sort(function(a, b) {
return a.label - b.label;
})
console.log(oldArray)
You can use collection sort method provided by lodash. https://lodash.com/docs/4.17.4#sortBy
var users = [{
"name": "[C US Equity] CITIGROUP INC",
"stats": [
{
"label": "DTD",
"value": null
},
{
"label": "MTD",
"value": null
},
{
"label": "YTD",
"value": 0.0536530913792681
},
{
"label": null,
"value": 0.18102519526139493
},
{
"label": "2015",
"value": -0.012946569977188238
},
{
"label": "dtd",
"value": null
}
]
}]
console.log(_.sortBy(users[0].stats, [function(o) { if(o.label){return o.label.toUpperCase();} }]));
This takes case of null values too.
I think this post may help you.
Take a look of it, it teaches you about how compare works.
All you need to do is to put that JSON thing into an object array,
then compare the value of YTD(make two for-loops, result [i] .stats [j] .label === 'YTD') to make the array to re-order it.
A comparison function is work like below(extracted from the above link)
function CompareNumbers( v1, v2 ) {
if ( v1 < v2 ) return -1; // v1 goes nearer to the top
if ( v1 > v2 ) return 1; // v1 goes nearer to the bottom
return 0; // both are the same
}
when it return -1(or sometimes false), the former one will be pushed to the front of your array, meanwhile 1 or true will push the former one to the back. And 0 (means not true or false, or you can handle the exception by yourself, push back or forward) will happen nothing.
But becare if your array exist two 'YTD' labelled value, if it happens it will make two value to appear in the same data.
This may help you in sorting the data while you cannot directly get a sorted data from your db server.
Oh, forgot to say, the compare function can compare the whole object.(of course you need to extract something like this ---> object[index].['Something your needed']), not only numbers.