How to convert object into array with lodash - javascript

I have below object
{
"holdings": [
{
"label": "International",
"value": 6
},
{
"label": "Federal",
"value": 4
},
{
"label": "Provincial",
"value": 7
}
]
}
I want to convert it into below object with lodash
{
"holdings": [
[
"International",
6
],
[
"Federal",
4
],
[
"Provincial",
7
],
[
"Corporate",
7
]
]
}
is there any way to change it. Please suggest.

If you want to use only lodash, then you can do it with _.mapValues and _.values to get the result, like this
console.log(_.mapValues(data, _.partial(_.map, _, _.values)));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }
The same can be written without the partial function, like this
console.log(_.mapValues(data, function(currentArray) {
return _.map(currentArray, _.values)
}));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }

This works recursively (So has to be called on the holdings property if you want to keep that) and "understands" nested objects and nested arrays. (vanilla JS):
var source = {
"holdings": [
{
"label": "International",
"value": 6
},
{
"label": "Federal",
"value": 4
},
{
"label": "Provincial",
"value": 7
}
]
}
function ObjToArray(obj) {
var arr = obj instanceof Array;
return (arr ? obj : Object.keys(obj)).map(function(i) {
var val = arr ? i : obj[i];
if(typeof val === 'object')
return ObjToArray(val);
else
return val;
});
}
alert(JSON.stringify(ObjToArray(source.holdings, ' ')));

Related

Javascript : How to remove object Item from nested Object Array? [duplicate]

This question already has answers here:
Filtering array of objects with arrays based on nested value
(8 answers)
Closed last month.
I need to remove one item from nested object array by filtering key value
sample json
[
{
"featureID": "e0152c71-657f-4bc2-b7f5-77e4d5a2a5a0",
"feature": "TestTwo",
"type": "TestTwo",
"rules": [
{
"ruleId": "89919182-feb1-402c-b9ad-03ae62586f84",
"ruleName": "Machine Guarding",
"featureName": "TestTwo",
"parameters": [
]
},
{
"ruleId": "e5361f7f-d8ae-424d-b781-a01987111181",
"ruleName": "Eye&Face Protection",
"featureName": "TestTwo",
"parameters": [
]
},
]
},
{
"featureID": "67d6e1bf-3919-4dcc-b636-236ab41d431b",
"feature": "TestThree",
"type": "TestThree",
"rules": [
{
"ruleId": "4e00e08e-6a34-47cf-9012-0800bc0063f2",
"ruleName": "Maximum People",
"featureName": "TestThree",
"parameters": [
]
},
{
"ruleId": "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
"ruleName": "Redzone",
"featureName": "TestThree",
"parameters": [
]
}
]
},
]
In above JSON, I need to remove an item from "rules" array by "ruleId" property.
i.e : remove "ruleName":"Machine Guarding" item by that ruleId property.
I tried below
deleteItems(argId){
this.done.find((items,d)=>items.feature == argID.featureName).rules.filter((int,ind)=>int.ruleId == argID.ruleId)
}
The above function passes the respective "ruleId" property.
const data=[{featureID:"e0152c71-657f-4bc2-b7f5-77e4d5a2a5a0",feature:"TestTwo",type:"TestTwo",rules:[{ruleId:"89919182-feb1-402c-b9ad-03ae62586f84",ruleName:"Machine Guarding",featureName:"TestTwo",parameters:[]},{ruleId:"e5361f7f-d8ae-424d-b781-a01987111181",ruleName:"Eye&Face Protection",featureName:"TestTwo",parameters:[]}]},{featureID:"67d6e1bf-3919-4dcc-b636-236ab41d431b",feature:"TestThree",type:"TestThree",rules:[{ruleId:"4e00e08e-6a34-47cf-9012-0800bc0063f2",ruleName:"Maximum People",featureName:"TestThree",parameters:[]},{ruleId:"a9ab3ce2-e69c-4c0c-b561-1107baed1e68",ruleName:"Redzone",featureName:"TestThree",parameters:[]}]}];
const deleteItems = (ruleIdToFilter) => {
return data.map((item) => {
item.rules = item.rules.filter((rule) => ruleIdToFilter != rule.ruleId);
return item;
});
};
let response = deleteItems("89919182-feb1-402c-b9ad-03ae62586f84");
console.log(response);

Function on specific key in nested object

How do I apply the multiply function on all values with the key colorScheme in the below nested object? Thus, returning the same array with the colorScheme changed from 10 --> 20? The object has a variable length for each rep.
function multiply(el) {
return el * 2
}
var array = {
"rep1": {
"type": [
"cartoon"
],
"colorScheme": [10]
},
{
"rep2": {
"type": [
"cartoon"
],
"colorScheme": [10]
},
"rep3": {
"type": [
"cartoon"
],
"color": [
"green"
]
}
}
You will need to be a bit creative with reduce, map and the spread (...) operator.
function multiply(el) {
return el * 2
}
var array = {
"rep1": {
"type": [
"cartoon"
],
"colorScheme": [10]
},
"rep2": {
"type": [
"cartoon"
],
"colorScheme": [10]
},
"rep3": {
"type": [
"cartoon"
],
"color": [
"green"
]
}
}
var result = Object.entries(array).reduce( (acc, [key, value]) => {
if(value.colorScheme)
acc[key] = {...value, colorScheme: value.colorScheme.map(multiply)};
else
acc[key] = {...value};
return acc;
},{})
console.log(result)
you can try this:
function multiply(el){
return el * 2
}
const nestedObject = {
"rep1": {
"type": [
"cartoon"
],
"colorScheme": [10]
},
"rep2": {
"type": [
"cartoon"
],
"colorScheme": [10]
},
"rep3": {
"type": [
"cartoon"
],
"color": [
"green"
]
}
}
for (const key of Object.keys(nestedObject)){
if(nestedObject[key].colorScheme)
nestedObject[key].colorScheme = nestedObject[key].colorScheme.map(multiply)
}
console.log(nestedObject)

Javascript array of arrays that contains obj, take only arrays that contain an obj with a specific key

I have array of arrays that contains obj, I should only take arrays that contain an obj with a specific key.
I tried to use a double filter but it doesn't work.
Can you give me some advice?
let result = [
[
{
"id": 1
},
{
"id": 2
}
],
[
{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[
{
"id": 6,
"type": {
"id": 5456
}
}
]
];
const c = result.filter(array => array.filter(a => a.hasOwnProperty('type') === true));
console.log(c);
Result:
[
[
{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[
{
"id": 6,
"type": {
"id": 5456
}
}
]
]
The filter in your filter function is wrong because you don't want to return a new collection, you want to return a boolean expression. Array.some() helps and checks if any item in that subarray has this property.
let result = [
[{
"id": 1
},
{
"id": 2
}
],
[{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[{
"id": 6,
"type": {
"id": 5456
}
}]
];
const validArrays = result.filter(subArray => subArray.some(item => item.hasOwnProperty('type')));
console.log(validArrays);
You'll have to check whether the length of the return value from the inner array is > 0. Only if the length of the return value from the inner filter is > 0 the outer filter returns true and store it into validArrays.
let result = [[{"id":1},{"id":2}],[{"id":3},{"id":4},{"id":5,"type":{"id":1555}}],[{"id":6,"type":{"id":5456}}]];
const validArrays = result.filter(subarray => subarray.filter(item => item.hasOwnProperty('type') === true).length > 0);
console.log(validArrays);

How to find the value nested inside an array of objects

Here I have to get value of file_info, I tried doing it using array.includes and array.find(), but got undefined.
My confusion here is related to, under 'facts', the first value is "==", then it has array of values associated to it. I could not figure out to find the values inside that nested object.
I even tried array.find(facts).contains(fileinfo) that did not work as well.
How can I solve this ??
"data": [
{
"task-id": "126e7267",
"type": "A",
"output": {...}
},
{
"task-id": "bdfddff3",
"type": "B",
"output": {
"id": "12b54370",
"facts": [
{
"==": [
"A",
{
"#type": "AA",
"#value": {
"id": "12b54370-4594-4033-a299-5480b593ee6d",
"facts": [
{
"==": [
"time",
1575759643.904254
]
},
{
"==": [
"mime",
"text/plain"
]
},
{
"==": [
"owner",
1000
]
},
{
"==": [
"size",
100
]
},
{
"==": [
"file_info",
"a0s5b2e6e739" // have to find and return this value
]
},
{
"==": [
"time",
{
"#value": "2019-12-07T23:01:50.703Z",
"#type": "timestamp"
}
]
},
],
}
}
]
},
....
]
}
},
{
"task-id": "5f557eac",
"type": "C",
....
},
],
I have tried to validate your json string. It seems to be invalid. For answering this question , i would assume below string to be your json :
{"data":[{"task-id":"126e7267","type":"A","output":{}},{"task-id":"bdfddff3","type":"B","output":{"id":"12b54370","facts":[{"==":["A",{"#type":"AA","#value":{"id":"12b54370-4594-4033-a299-5480b593ee6d","facts":[{"==":[{"time":{"#value":"1575759643.904254"}}]},{"==":["mime","text/plain"]},{"==":["owner",1000]},{"==":["size",100]},{"==":[{"file_info":"a0s5b2e6e739"}]},{"==":["time",{"#value":"2019-12-07T23:01:50.703Z","#type":"timestamp"}]}]}}]}]}},{"task-id":"5f557eac","type":"C"}]}
I had tried to figure out a repetative pattern in your json but since "#value" tag is seen inside only one "facts" object below code should help you getting started . For given json , below code prints the value of "file_info"(Here , i'am assuming that "file_info" should be followed by a colon(:) i.e. "a0s5b2e6e739" is the value you are looking for) :
var jsonStr = '{"data":[{"task-id":"126e7267","type":"A","output":{}},{"task-id":"bdfddff3","type":"B","output":{"id":"12b54370","facts":[{"==":["A",{"#type":"AA","#value":{"id":"12b54370-4594-4033-a299-5480b593ee6d","facts":[{"==":[{"time":{"#value":"1575759643.904254"}}]},{"==":["mime","text/plain"]},{"==":["owner",1000]},{"==":["size",100]},{"==":[{"file_info":"a0s5b2e6e739"}]},{"==":["time",{"#value":"2019-12-07T23:01:50.703Z","#type":"timestamp"}]}]}}]}]}},{"task-id":"5f557eac","type":"C"}]}';
var jsonObj = JSON.parse(jsonStr);
//If there is a repetative pattern , you can replace this hard coding with your pattern.
var objArray = jsonObj["data"][1]["output"]["facts"][0]["=="][1]["#value"]["facts"];
console.log(objArray);
if(objArray && objArray.length >0){
for(let i =0;i<objArray.length;i++){
if(objArray[i] && objArray[i]["=="] && objArray[i]["=="].length > 0 && objArray[i]["=="][0]["file_info"]){
//here "file_info" is fetched
console.log('here ',objArray[i]["=="][0]["file_info"]);
}
}
}
Hope above code helps you to get started.
You can map and filter the object/array to get the result if the format is fixed. Here, I am writing to a Map and retrieving the property I need at the very end.
let data = [
{
"task-id": "126e7267",
"type": "A",
"output": {}
},
{
"task-id": "bdfddff3",
"type": "B",
"output": {
"id": "12b54370",
"facts": [
{
"==": [
"A",
{
"#type": "AA",
"#value": {
"id": "12b54370-4594-4033-a299-5480b593ee6d",
"facts": [
{
"==": [
"time",
1575759643.904254
]
},
{
"==": [
"mime",
"text/plain"
]
},
{
"==": [
"owner",
1000
]
},
{
"==": [
"size",
100
]
},
{
"==": [
"file_info",
"a0s5b2e6e739" // have to find and return this value
]
},
{
"==": [
"time",
{
"#value": "2019-12-07T23:01:50.703Z",
"#type": "timestamp"
}
]
},
],
}
}
]
}
]
}
},
{
"task-id": "5f557eac",
"type": "C",
"output": {}
}
]
const map = new Map()
const facts = data
.map(d => d.output)
.filter(o => o.hasOwnProperty('facts'))
.map(d => d.facts)
.map(i => i[0]["=="][1])
.map(d => d["#value"].facts)
const item = facts.forEach(o => o.forEach(i => map.set(i["=="][0], i["=="][1])))
console.log(map.get("file_info"))

how to access a JSON object? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
i have this JSON Object, and i wanna access to this > object.foda.forta.id or name.. in JAVASCRIPT
thanks
note: this json it's created by xml2js.Parser()
{
"object": {
"foda": [
{
"forta": [
{
"id": [
"1"
],
"name": [
"dasdghjg"
]
},
{
"id": [
"2"
],
"name": [
"jj"
]
},
{
"id": [
"3"
],
"name": [
"gjhjg"
]
}
]
}
]
}
}
You cant access by object.foda.forta.id
as foda and fotra are lists, you can access by object.foda[0].forta[0].id
Note - 0 is used for sample only you can use any index (less the size of array)
Your JSON was terribly created, lots of unnecessary Arrays, but you can access it like this:
var obj = {
"object": {
"foda": [
{
"forta": [
{
"id": ["1"],
"name": ["dasdghjg"]
},
{
"id": ["2"],
"name": ["jj"]
},
{
"id": ["3"],
"name": ["gjhjg"]
}
]
}
]
}
};
document.body.innerHTML = "ID: " + obj.object.foda[0].forta[0].id[0] + " - Name: " + obj.object.foda[0].forta[0].name[0];
Take a look at this fiddle!

Categories