Hey guys i really strongly to convert this array , can somebody help me out?
[ {
"0":{"name":"a","available":"12","onOrder":"0",},
"1"{"name":"b","available":"3","onOrder":"0","},
"2"{"name":"c","available":"0","onOrder":"3"},
"3"{"name":"d","available":"2","onOrder":"2"}
} ]
how to map or convert to
[ {"name":"a","available":"12","onOrder":"0",},
{"name":"b","available":"3","onOrder":"0","},
{"name":"c","available":"0","onOrder":"3"},
{"name":"d","available":"2","onOrder":"2"}
]
The original example input has a few syntactical issues so I am not sure as to what the "array" and its elements look like. Making an assumption to make it syntactically compliant with the fewest modifications leads to the array in the working example below. Based on that input, using Object.values is the simplest way to get the desired output.
const arr = [{
"0": {
"name": "a",
"available": "12",
"onOrder": "0",
},
"1": {
"name": "b",
"available": "3",
"onOrder": "0"
},
"2": {
"name": "c",
"available": "0",
"onOrder": "3"
},
"3": {
"name": "d",
"available": "2",
"onOrder": "2"
}
}];
console.log(Object.values(arr[0]));
EDIT: Updated to show ES2015 compatible solution
const arr = [{
"0": {
"name": "a",
"available": "12",
"onOrder": "0",
},
"1": {
"name": "b",
"available": "3",
"onOrder": "0"
},
"2": {
"name": "c",
"available": "0",
"onOrder": "3"
},
"3": {
"name": "d",
"available": "2",
"onOrder": "2"
}
}];
console.log(Object.keys(arr[0]).map(k => arr[0][k]));
You can use Array.prototype.map()
const arr = [
{ "0": {"name":"a","available":"12","onOrder":"0"} },
{ "1": {"name":"b","available":"3","onOrder":"0" } },
{ "2": {"name":"c","available":"0","onOrder":"3" } },
{ "3": {"name":"d","available":"2","onOrder":"2"} }
];
const newArr = arr.map((item, index) => {
return item[index];
});
console.log(newArr);
More complex solution will be
const arr = [{
'0': {
'name': 'a',
'available': '12',
'onOrder': '0'
},
'1': {
'name': 'b',
'available': '3',
'onOrder': '0'
},
'2': {
'name': 'c',
'available': '0',
'onOrder': '3'
},
'3': {
'name': 'd',
'available': '2',
'onOrder': '2'
}
}]
const arr2 = arr.reduce((arr, item) => [...arr, ...Object.values(item)], [])
console.log(arr2)
Related
I need to find value of type2.id where id is 7 in the following object
[
{
"type1": {
"id": "1",
"value": "val1"
},
"type2": [
{
"id": "2",
"value": "val2"
}
]
},
{
"type1": null,
"type2": [
{
"id": "5",
"value": "val5"
}
]
},
{
"type1": {
"id": "3",
"value": "val3"
},
"type2": [
]
},
{
"type1": {
"id": "4",
"value": "val4"
},
"type2": [
{
"id": "7",
"value": "val7"
}
]
}
]
Please notice type1 is a simple object and type 2 is an array here, there can be empty array in type2 as well.
arr.find(({type2}) => type2[0]?.id === '7')?.type2[0].value
let value = null;
// First way using forEach
obj.forEach(item => {
if (item.type2 && item.type2.length > 0) {
item.type2.forEach(type2 => {
if (type2.id === '7') {
value = type2.value;
}
});
}
});
console.log("first way : ", value);
// Second way using map and filter
let type2Array = obj.map(obj => obj.type2).flat()
value = type2Array.filter(obj => obj.id === '7').at(0)?.value
console.log("second way : ", value);
<script>
const obj = [{
"type1": {
"id": "1",
"value": "val1"
},
"type2": [{
"id": "2",
"value": "val2"
}]
},
{
"type1": null,
"type2": [{
"id": "5",
"value": "val5"
}]
},
{
"type1": {
"id": "3",
"value": "val3"
},
"type2": [
]
},
{
"type1": {
"id": "4",
"value": "val4"
},
"type2": [{
"id": "7",
"value": "val7"
}]
}
];
</script>
Try this
const data = [
{
type1: {
id: "1",
value: "val1",
},
type2: [
{
id: "2",
value: "val2",
},
],
},
{
type1: null,
type2: [
{
id: "5",
value: "val5",
},
],
},
{
type1: {
id: "3",
value: "val3",
},
type2: [],
},
{
type1: {
id: "4",
value: "val4",
},
type2: [
{
id: "7",
value: "val7",
},
],
},
];
const result = data.find((object) => {
const { type2 } = object;
if (!type2) {
return false;
}
const [ firstFromType2 ] = type2;
if (!firstFromType2) {
return false;
}
return firstFromType2.id === '7';
});
console.log(result);
const data = [{"type1":{"id":"1","value":"val1"},"type2":[{"id":"2","value":"val2"}]},{"type1":null,"type2":[{"id":"5","value":"val5"}]},{"type1":{"id":"3","value":"val3"},"type2":[]},{"type1":{"id":"4","value":"val4"},"type2":[{"id":"7","value":"val7"}]}]
console.log(data.flatMap(i=>i.type2).find(({id})=>id==='7')?.value)
Assign the array to a const and make a nested map.
const foundObj = array.map(obj => obj.type2.map(type2obj => type2obj.id === '7')));
const value = foundObj.value
fiddle here: https://jsfiddle.net/
Need a help from Ramda community... I have an object array that I need to sort by "chapter_id" and after sorting, just remove "chapter_id":
const stuff = [
{ id: 1, title: "hello world", chapter_id: "4321" },
{ id: 2, title: "new title", chapter_id: "21" },
{ id: 3, title: "...", chapter_id: "33" },
{ id: 4, title: "huh!?", chapter_id: "14" },
{ id: 5, title: "From Earth", chapter_id: "11" },
{ id: 6, title: "alien", chapter_id: "11" },
{ id: 7, title: "Saturn", chapter_id: "11" },
{ id: 8, title: "Mars:/", chapter_id: "21" },
{ id: 9, title: "damn", chapter_id: "3" },
{ id: 10, title: "test", chapter_id: "11" },
{ id: 11, title: "ramda heeeelp", chapter_id: "31" },
{ id: 12, title: "hello?", chapter_id: "21" }
]
And as result I want to get this object:
{
"3": [
{
"id": "9",
"title": "damn"
}
],
"11": [
{
"id": "5",
"title": "From Earth"
},
{
"id": "6",
"title": "alien"
},
{
"id": "7",
"title": "Saturn"
},
{
"id": "10",
"title": "test"
}
],
"14": [
{
"id": "4",
"title": "huh!?"
}
],
"21": [
{
"id": "2",
"title": "new title"
},
{
"id": "8",
"title": "Mars:/"
},
{
"id": "12",
"title": "hello?"
}
],
"31": [
{
"id": "11",
"title": "ramda heeeelp"
}
],
"33": [
{
"id": "3",
"title": "..."
}
],
"4321": [
{
"id": "1",
"title": "hello world"
}
]
}
How I struggled with this:
let object = {};
map(({ chapter_id }) => {
const composed = compose(
map(evolve({ id: toString })), //here id is converted to a string
filter(c => c.chapter_id === chapter_id),
);
object[chapter_id] = composed(stuff)
}, stuff);
My result:
{
"3": [
{
"id": "9",
"title": "damn",
"chapter_id": "3" //Dissoc this
}
],
"11": [
{
"id": "5",
"title": "From Earth",
"chapter_id": "11" //dissoc this
},
{
"id": "6",
"title": "alien",
"chapter_id": "11" //and this
},
{
"id": "7",
"title": "Saturn",
"chapter_id": "11" //and this
},
{
"id": "10",
"title": "test",
"chapter_id": "11" //and this
}
],
"14": [
{
"id": "4",
"title": "huh!?",
"chapter_id": "14" //and this
}
],
"21": [
{
"id": "2",
"title": "new title",
"chapter_id": "21" //and this
},
{
"id": "8",
"title": "Mars:/",
"chapter_id": "21" //and this
},
{
"id": "12",
"title": "hello?",
"chapter_id": "21" //and this
}
],
"31": [
{
"id": "11",
"title": "ramda heeeelp",
"chapter_id": "31" //and this!!!!!!
}
],
"33": [
{
"id": "3",
"title": "...",
"chapter_id": "33" //and this..
}
],
"4321": [
{
"id": "1",
"title": "hello world",
"chapter_id": "4321" //and this:(
}
]
}
It works but I can't dissoc "chapter_id" from each object, does anyone know how to solve this? :Δ
With Ramda you can group by the key, and then map the groups, and dissoc the key from all objects:
const { pipe, groupBy, prop, map, dissoc } = R;
const fn = key => pipe(
groupBy(prop(key)), // group by the key
map(map(dissoc(key))) // remove the key from all objects in all groups
);
const stuff = [{"id":1,"title":"hello world","chapter_id":"4321"},{"id":2,"title":"new title","chapter_id":"21"},{"id":3,"title":"...","chapter_id":"33"},{"id":4,"title":"huh!?","chapter_id":"14"},{"id":5,"title":"From Earth","chapter_id":"11"},{"id":6,"title":"alien","chapter_id":"11"},{"id":7,"title":"Saturn","chapter_id":"11"},{"id":8,"title":"Mars:/","chapter_id":"21"},{"id":9,"title":"damn","chapter_id":"3"},{"id":10,"title":"test","chapter_id":"11"},{"id":11,"title":"ramda heeeelp","chapter_id":"31"},{"id":12,"title":"hello?","chapter_id":"21"}];
const result = fn('chapter_id')(stuff);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
As Ori Drori notes, this is the likely Ramda method:
const transform = pipe (
groupBy(prop('chapter_id')),
map(map(dissoc('chapter_id'))),
)
But if you need to actually sort the keys, as your answer suggests, then it will take a bit more processing. You might try something like this:
const transform = pipe (
groupBy(prop('chapter_id')),
map(map(dissoc('chapter_id'))),
toPairs,
sortBy(pipe(head, Number)),
fromPairs
)
const stuff = [{id: 1, title: "hello world", chapter_id: "4321"}, {id: 2, title: "new title", chapter_id: "21"}, {id: 3, title: "...", chapter_id: "33"}, {id: 4, title: "huh!?", chapter_id: "14"}, {id: 5, title: "From Earth", chapter_id: "11"}, {id: 6, title: "alien", chapter_id: "11"}, {id: 7, title: "Saturn", chapter_id: "11"}, {id: 8, title: "Mars: /", chapter_id: "21"}, {id: 9, title: "damn", chapter_id: "3"}, {id: 10, title: "test", chapter_id: "11"}, {id: 11, title: "ramda heeeelp", chapter_id: "31"}, {id: 12, title: "hello?", chapter_id: "21"}]
console.log (
transform (stuff)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script> const {pipe, groupBy, prop, map, dissoc, toPairs, sortBy, head, fromPairs} = R </script>
That sorting line could be written in many ways. Perhaps
sort(lift(subtract)(head, head)),
or just
sort(([a], [b]) => a - b),
And obviously if you were so inclined, you could pull out a sortByKeys function like this:
const sortByKeys = (fn) => pipe(toPairs, sortBy(fn), fromPairs)
sortByKeys is not a likely candidate for inclusion in Ramda, which really prefers to think of objects as unordered collections of name-value pairs. But it could easily go in your own helper library.
First of all the finite task is not properly described :) What you really want (based on the result I want to get section) is to normalize (or restructure) the array of objects into an object, which have the chapter_id as a key, and the value is an array of the associated records of the stuff array with that chapter_id
On my opinion, your solution is cool and seems like a more functional, but in this particular case I've probably will give a preference to the simple reduce function, which is more readable...
reduce((acc, {chapter_id, ...rest}) => {
const isInitialized = !!acc[chapter_id];
if (isInitialized) {
acc[chapter_id].push(rest);
} else {
acc[chapter_id] = [rest];
}
return acc;
}, {}, stuff);
This is my json object:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
I want my output like this:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [1,2] // this 1 and 2 is coming from categoriesservices array inside the category object i have id
}
How to do this using map function? I am new to javascript, which is good approach map or forloop?
See destructuring assignment, Array.prototype.map(), and JSON for more info.
// Input.
const input = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
// Categories => Objects to Cats => Ids.
const output = (input) => JSON.parse(JSON.stringify({
...input,
cats: input.categoryservices.map(({category: {id}}) => id),
categoryservices: undefined
}))
// Log.
console.log(output(input))
If you are not worried about original object immutability, then try this
obj['cats'] = obj['categoryservices'].map(cat => cat.category.id);
delete obj['categoryservices'];
console.log(obj);
I just use .map() on categoryservices array:
var output = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
output.cats = output.categoryservices.map((element) =>
element.category.id);
delete output.categoryservices;
console.log(JSON.stringify(output));
use .map() , it return value as array ! You want to change is categoryservices key only ! So delete that after you get wanted value ..
var output = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
output.cats = output.categoryservices.map(i => i.category.id );
delete output.categoryservices;
console.log(output);
Try this working demo :
var jsonObj = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
var arr = jsonObj.categoryservices.map(item => item.category.id)
jsonObj.cats = arr;
delete jsonObj.categoryservices;
console.log(jsonObj);
Try this
var testData={
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
testData.cats=[];
testData.categoryservices.forEach(function (item) {
testData.cats.push(item.category.id);
});
delete testData.categoryservices;
console.log(testData);
You can try using jquery each:
<div id="log"></div>
var conversation = {
'John': {
1: 'Test message 1',
2: 'Test message 2',
'Reply': {
3: 'Test message 3',
4: 'Test message 4'
}
},
'Jack': {
5: 'Test message 5',
6: 'Test message 6'
}
};
function iterate(obj) {
if (typeof obj === 'string') {
$('#log').append((obj + '<br/>'));
}
if (typeof obj === 'object') {
$.each(obj, function(key, value) {
iterate(value);
});
}
}
iterate(conversation);
I have a Json data that I need adjust before sending it to my component. My Json is as below. I need to identify the missing fields and move the below ones up.
[{
"Id": "a",
"ColumnLocation": "0",
"RowLocation": "0"
}, {
"Id": "b",
"ColumnLocation": "0",
"RowLocation": "1"
},
{
"Id": "4",
"ColumnLocation": "0",
"RowLocation": "3"
},
{
"Id": "c",
"ColumnLocation": "1",
"RowLocation": "0"
}, {
"Id": "d",
"ColumnLocation": "1",
"RowLocation": "2"
}, {
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "0"
},
{
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "2"
}]
My required Json is:
[{
"Id": "a",
"ColumnLocation": "0",
"RowLocation": "0"
}, {
"Id": "b",
"ColumnLocation": "0",
"RowLocation": "1"
},
{
"Id": "4",
"ColumnLocation": "0",
"RowLocation": "2"
},
{
"Id": "c",
"ColumnLocation": "1",
"RowLocation": "0"
}, {
"Id": "d",
"ColumnLocation": "1",
"RowLocation": "1"
}, {
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "0"
},
{
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "1"
}]
Here after (0,0), (0,1), property (0,2) is missing so I need to move it up and make it (0,2).. Same way after(1,0), property(1,1) is missing so it has to be (1,1).
I tried writing a custom function for this, but couldn't able to achieve it, so thought any map function that fits this scenario
I am getting gadgets information from the API. In some cases, some gadgets might be missing, so I need to pull there location up and draw the gadgets.
this.userService.getGadgets(id).subscribe(gadgets => { this.res = gadgets.map(function (v) { return v.ColumnLocation; });
// required logic ************/
for (let gadget of gadgets) {
this.dashboardsText = "";
switch (gadget.Name) {
You could store the last column and row, then check if it is not the same column, then reset row counter.
Then check if RowLocation is equal to row counter and if not set the new value.
Finally increment row counter.
var array = [{ Id: "a", ColumnLocation: "0", RowLocation: "0" }, { Id: "b", ColumnLocation: "0", RowLocation: "1" }, { Id: "4", ColumnLocation: "0", RowLocation: "3" }, { Id: "c", ColumnLocation: "1", RowLocation: "0" }, { Id: "d", ColumnLocation: "1", RowLocation: "2" }, { Id: "e", ColumnLocation: "2", RowLocation: "0" }, { Id: "e", ColumnLocation: "2", RowLocation: "2" }];
array.forEach(function (col, row) {
return function (o) {
if (col !== o.ColumnLocation) {
col = o.ColumnLocation;
row = 0;
}
if (+o.RowLocation !== row) {
o.RowLocation = row.toString();
}
row++;
}
}());
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use global variables instead if the closure, maybe this works for you.
var array = [{ Id: "a", ColumnLocation: "0", RowLocation: "0" }, { Id: "b", ColumnLocation: "0", RowLocation: "1" }, { Id: "4", ColumnLocation: "0", RowLocation: "3" }, { Id: "c", ColumnLocation: "1", RowLocation: "0" }, { Id: "d", ColumnLocation: "1", RowLocation: "2" }, { Id: "e", ColumnLocation: "2", RowLocation: "0" }, { Id: "e", ColumnLocation: "2", RowLocation: "2" }],
col,
row;
array.forEach(function (o) {
if (col !== o.ColumnLocation) {
col = o.ColumnLocation;
row = 0;
}
if (+o.RowLocation !== row) {
o.RowLocation = row.toString();
}
row++;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
};
var array, i;
array = [{"Id": "a","ColumnLocation": "0","RowLocation": "0"}, {
"Id": "b","ColumnLocation": "0", "RowLocation": "1"}]
i = array.length;
while (i--) {
if (!array[i].ColumnLocation) {
array.move(i, i+1);
}
Was wondering if anyone knows of a way to use lodash, or vanilla JS to achieve this small problem?
I have this starting object:
{
"1": {
"null": {
"2": {
"3": {
"6": {
"7": "c"
},
"null": {
"null": {
"5": "b"
}
}
}
}
}
},
"8": {
"10": "e",
"null": {
"9": "d"
}
}
}
Each level (horizontally) means something. So level 1 is of type A, level 2 is of type B, 3 of type A, 4 of type B and so forth. So it alternates.
Is there a nice and simply way to "collapse" this object to look something like this:
[
{
"type": "A",
"label": "1",
"children": [
{
"type": "A",
"label": "2",
"children": [
{
"type": "B",
"label": "3",
"children": [
{
"type": "A",
"label": "6",
"children": [
{
"type": "A",
"label": "7",
"value": "c"
}
]
},
{
"type": "A",
"label": "8",
"children": [
{
"type": "A",
"label": "5",
"value": "b"
}
]
}
]
}
]
}
]
},
{
"type": "A",
"label": "8",
"children": [
{
"type": "B",
"label": "10",
"value": "e"
},
{
"type": "A",
"label": "9",
"value": "d"
}
]
}
]
In essence annotating each level with what type it is, and nesting its children.
Here is the code
function transformObj(obj, level) {
level = level || 1;
var result = _(obj).transform(function(result, value, key) {
var obj = {
type: (level % 2 === 0) ? 'B' : 'A',
label: key
};
if (key === 'null') {
result.push(transformObj(value, level+1));
} else {
if (_.isObject(value)) {
obj.children = transformObj(value, level+1);
} else {
obj.value = value;
}
result.push(obj);
}
}, [])
.flatten()
.value();
return result;
}
Here is the output
[
{
"type": "A",
"label": "1",
"children": [
{
"type": "A",
"label": "2",
"children": [
{
"type": "B",
"label": "3",
"children": [
{
"type": "A",
"label": "6",
"children": [
{
"type": "B",
"label": "7",
"value": "c"
}
]
},
{
"type": "A",
"label": "5",
"value": "b"
}
]
}
]
}
]
},
{
"type": "A",
"label": "8",
"children": [
{
"type": "B",
"label": "10",
"value": "e"
},
{
"type": "A",
"label": "9",
"value": "d"
}
]
}
]
This should do the trick:
var source = {
"1": {
"null": {
"2": {
"3": {
"6": {
"7": "c"
},
"null": {
"null": {
"5": "b"
}
}
}
}
}
},
"8": {
"10": "e",
"null": {
"9": "d"
}
}
};
function collapse(obj, parent, level){
var result = parent || [];
level = level || 0;
for(prop in obj){
var item = obj[prop];
var build = {
type : level % 2 ? "B" : "A",
label : prop
//, level : level
}
if(typeof item == 'object'){
build.children = [];
collapse(item, build.children, level + 1);
} else {
build.value = item;
}
result.push(build);
}
return result;
}
var output = collapse(source);
var result = JSON.stringify(output, null, ' ');
console.log(result);
var elem = document.getElementById("result");
elem.innerHTML = result;
<pre id="result"></pre>
function doIt(data){
return _.chain(data)
.transform(function(result, value, key){
if(key !== 'null'){
var type = _.parseInt(key) % 2 === 1 ? 'A' : 'B';
if(_.isObject(value) && !_.includes(_.keys(value), 'prop1')){
result.push({
type: type,
label: key,
children: doIt(value)
});
} else {
result.push({
type: type,
label: key,
value: value
});
}
} else {
if(_.isObject(value)){
result.push(doIt(value));
}
}
}, [])
.flatten()
.value();
}
var result = doIt(data);
result is
[
{
"type": "A",
"label": "1",
"children": [
{
"type": "B",
"label": "2",
"children": [
{
"type": "A",
"label": "3",
"children": [
{
"type": "B",
"label": "6",
"children": [
{
"type": "A",
"label": "7",
"value": "c"
}
]
},
{
"type": "A",
"label": "5",
"value": "b"
}
]
}
]
}
]
},
{
"type": "B",
"label": "8",
"children": [
{
"type": "B",
"label": "10",
"value": "e"
},
{
"type": "A",
"label": "9",
"value": "d"
}
]
}
]