How to get the array of the data in JSON - JavaScript [duplicate] - javascript

This question already has answers here:
Getting JavaScript object key list
(19 answers)
Closed 3 years ago.
Hello I was trying to get the array of the data which was written in JSON
For example this is my JSON object
{
Data1 : {
Data2 : "hello",
Data3 : "hi"
},
Data4 : {
Data5 : "this is Karan",
}
}
I want the output as an array which contains [Data1, Data4]
Is there any way to do this Thank you

It's simple using Object.keys()
The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.
var json = {
Data1 : {
Data2 : "hello",
Data3 : "hi"
},
Data4 : {
Data5 : "this is Karan",
}
}
var keys = Object.keys(json);
console.log(keys);

You can do it in two ways. Either use Object.keys or you can use for..in loop to iterate the object and return push the keys in an array
let data = {
Data1: {
Data2: "hello",
Data3: "hi"
},
Data4: {
Data5: "this is Karan",
}
}
/**** OPTION -1 *****/
let getKeys = Object.keys(data);
console.log('Option-1 Result ', getKeys)
/**** OPTION -2 *****/
let keysArray = [];
for (let keys in data) {
keysArray.push(keys)
};
console.log(keysArray)

Related

How to find duplicate values in object and push in array to create distinct array of objects in Angular8 [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed last year.
I am getting below response from API, but i want to format it for iteration to reach the correct values.
In below objects, i am getting column makeLineName and based on this column, i want to create one types array and push whole object as it is on types array.
Suppose for ex - In below response, We have 2 objects for "makeLineName":"Red", So i want to create one types array and push all object inside types array whose matching makeLineName = Red. Thats it.
const data = [{
"makeLineName":"Red",
"country":"Germany",
"processTypeId":"3",
"processTechType":"Batch & crunch"
},
{
"makeLineName":"Red",
"country":"Germany",
"processTypeId":"3",
"processTechType":"Batch"
},
{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
}
];
Expected Output
const data = [{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch & crunch"
types :[{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch & crunch"
},
{
"makeLineName":"Red",
"processTypeId":"3",
"country":"Germany",
"processTechType":"Batch"
}]
},
{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
types :[{
"makeLineName":"Blue",
"country":"India",
"processTypeId":"3",
"processTechType":"Continues"
}
}];
I did below code, it was working fine, but it is creating many nested arrays for types and because of this i am facing issue in iterating with loop to get the perfect value of types array.
getMakeLineMasterData() {
const data = {
data1: 'India'
};
this.testfile.getWork(data).pipe(map(data => this.processData(data))).subscribe((resp: any) => {
if (resp) {
console.log(this.dataSource, "resp");
}
});
}
processData(data: any) {
let mappedData = [];
for (const item of data) {
const mitem = mappedData.find(obj => obj.makeLineName == item.makeLineName);
if (mitem) {
mitem['types'].push(item);
} else {
let newItem = item;
newItem['types'] = [item];
mappedData.push(newItem);
}
}
return mappedData;
}
Right now my code is working and returning data but it is creating many nested arrays for types inside and inside likewise..
Can anyone help me to make it proper as per my expected output.
Issue: circular structure
You are pushing the array inside itself.
eg:
let object1 = { property: [] , cat:1 };
object1.property = [object1];
or
let object1 = { property: [object1] };
// here object1 is pointing to to itself, due to pass by reference.
//that is why you are seeing a never ending nesting of itself (circular);
Correction of your code:
let processData = (data: any) => {
let mappedData = [];
for (const item of data) {
const mitem = mappedData.find(obj => obj.makeLineName === item.makeLineName);
if (mitem) {
mitem['types'].push(item);
} else {
let newItem = { ... item }; //** creating a new object with copied properties
newItem['types'] = [item];
mappedData.push(newItem);
}
}
return mappedData;
}

Convert Json Array to single Object in Node JS [duplicate]

This question already has answers here:
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
How to concatenate properties from multiple JavaScript objects
(14 answers)
Closed 1 year ago.
I want to convert JSON array to a single object. PFB the details
Array:
[{ "item-A": "value-1" }, { "item-B": "value-2" }]
Expected Result:
{ "item-A": "value-1", "item-B": "value-2" }
I have tried following options but result is not what I was expecting
let json = { ...array };
json = Object.assign({}, array);
json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
Result:
{"0":{"item-A":"value-1"},"1":{"item-B":"value-2"}}
You can use Object.assign and spread the array
const arr=[{ "item-A": "value-1" }, { "item-B": "value-2" }];
console.log(Object.assign({},...arr));
You can use reduce like how you did it with more attention like this:
let array = [{ "item-A": "value-1" }, { "item-B": "value-2" }];
let object = array.reduce((prev, curr) => ({ ...prev, ...curr }), {});
console.log(object);

How do I turn the values from an object into an array?

I have a function that is polling for temperature data:
{"a":"43",
"b":"43",
"c":"42",
"d":"43",
"e":"40",
"f":"41",
"g":"100",
"h":"42.6"}
I want to be able to graph that data over time, but I can't figure out the best way to map the above data, to something like the below data:
temps: [{
name: "a",
data: ["43","42","43"]
},
name: "b",
data: ["43","42","43"]
},
etc...
]
I have tried the code below, and tried to figure out the javascript map function, but I keep running into scoping problems where "this" isn't the same thing as it was in the parent:
this.temp_names.forEach(function(e){
if(typeof this.temps[e] == "undefined") {
this.temps[e] = []
}
this.temps.e.unshift(this.sys_telemetry.S.temps)
if (this.temps.e.length > 10) {
this.temps.e.pop()
}
})
where "temp_names" was an array of the keys.
I'm doing this in VueJS, so the "this" is accessing the data in my component.
Using Array#from, Object#entries, Array#map and destructuring you could do something like this.
const data={"a":"43","b":"43","c":"42","d":"43","e":"40","f":"41","g":"100","h":"42.6"}
const res = Object.entries(data)
.map(([name, data])=>({name, data:[data]}));
console.log(res);
Alternative using Array#reduce, Map,
const data={"a":"43","b":"43","c":"42","d":"43","e":"40","f":"41","g":"100","h":"42.6"}
const res = Array.from(Object
.entries(data)
.reduce((a,[k,v])=>{
if(!a.has(k)) a.set(k, []);
a.get(k).push(v);
return a;
}, new Map()))
.map(([name, data])=>({name, data}));
console.log(res);
graph that data over time
Because you want to do this over time, it would make sense to create an array and then using Object.entries, & Array.find, update the results.
Here is an example.
const values1 =
{"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41",
"g":"100", "h":"42.6"};
const values2 =
{"c":"44", "e":"39"};
const results = [];
function addData(data) {
Object.entries(data).forEach(([k, v]) => {
let find = results.find(f => f.name === k);
if (!find) {
find = {
name: k,
data: []
}
results.push(find);
}
find.data.push(v);
});
}
addData(values1); //data packet one arrives
addData(values2); //data packet two arrives
console.log(results); //results contains both data packet one & two.
You might be able to get away with a simpler data structure like, eg. { a: [43, 42, 43], b: [1, 2, 3] }
ie. instead of having separate name and data keys, you could use name as the key, and the data array as the value.
If this would work to represent the timeline for each key, and your initial data is structured like, eg. [{ a: 43, b: 1, c: 3 }, { a: 42, b: 2, c: 3 }], then something like this might be suitable to transform the latter into the former:
const output = {};
temp_data.forEach(x => {
for (const key in x) {
const y = x[key];
if (typeof output[key] === 'undefined') {
output[key] = [];
}
output[key].push(y);
}
});
This produces an object whose keys match the keys in your data points (eg. "a", "b", "c", etc), and whose values are an array of all the values for each of these keys, which might be suitable for plotting a timeline.
(Incidentally, if you want to plot these as values on a graph, it might be better to treat the values as numbers - eg. 1, 2, 3 - rather than strings - eg. "1", "2", "3").
There are probably more elegant, functional-style ways of doing this, but this might do the job!
It seems to me that you want to be able to add multiple datasets to the data object. One approach is to have a data object with methods that know how to do things like add data to themselves, maybe something like the following. You might want to keep the index property private, and maybe sort it so it's always in a particular order regardless of the order the values are added.
var data0 = {"a":"43",
"b":"43",
"c":"42",
"d":"43"};
var data1 = {"a":"53",
"b":"53",
"c":"52",
"d":"53",
"e":"65"
};
class DataObject {
constructor (data) {
this.index = [];
this.data = [];
if (data) {
this.addData(data);
}
}
addData (data) {
Object.keys(data).forEach(key => {
let idx = this.index.indexOf(key);
if (idx == -1) {
idx = this.index.push(key) - 1;
this.data.push({name:key, data:[]});
}
this.data[idx].data.push(data[key]);
});
}
}
// Initialise object with some data
let myData = new DataObject(data0);
console.log(JSON.stringify(myData.data));
// Add more data
myData.addData(data1);
console.log(JSON.stringify(myData.data));

How to get value of key in same node level with JSON format

I have this JSON format structure
valuesColors : [{
key: "<75%",
color:"61C56E"
},
{
key: ">=75%&<90%",
color:"6144RF"
},
{
key: ">90%",
color:"333RTE"
}
]
I would get for exemple valuesColors.color of valuesColor.key == ">75%". the problem here I have the value in the same level of the key so I can't use .
You can't use . because your object is an array type and each element in that array is a json node. So you'd need to access the relevant index and then you can operate on the object.
let array = [{key: '1'}, {key: '2'}];
let jsonNode = array[0];
console.log(jsonNode.key);
console.log(array[0].key);
console.log(array[1].key);
console.log(array.key); // Will not work as this is an array, not a json object.
Array.find():
const result = valuesColors.find(entry => {
return entry.key == "<75%"; // or what ever logic
});
console.log(result.color); // -> 61C56E
https://stackblitz.com/edit/how-to-get-value-of-key-in-same-node-level-with-json-format?file=index.js

How can I filter by all the properties in an array of objects? [duplicate]

This question already has answers here:
Filter array of objects on all properties value
(3 answers)
Closed 5 years ago.
Suppose I have an array like this:
const people = [
{
"name":"pete22",
"age":56
},
{
"name":"sonya56",
"age":22
}
]
I can filter with lodash like this by name:
let result = people.filter(person =>_.includes(person.name,'56')
//{'name':'sonya56'}
What if I want to return all people with '56' in any property? So in the above example it would return both people? I am looking for a compact solution, maybe lodash?
You don't need Lodash to do this as JavaScript natively has support to do these kind of things.
What you need to do is filter the people but also filter each value inside an entry, e.g.:
const people = [{
"name": "pete22",
"age": 56
}, {
"name": "sonya56",
"age": 22
}]
// Filter your 'people' JSON
const filteredPeople = people.filter(person => {
// Filter each 'value' (property) inside each entry in 'people'
return Object.values(person).filter(value => {
// Turn a value into a string and check if it includes the value '56'
return value.toString().includes('56')
})
})
console.log(filteredPeople)
You could just use Array#filter with Object.values, Array#map with strings and check with Array#some and Array#includes.
const
people = [{ name: "pete22", age: 56 }, { name: "sonya56", age: 22 }],
filteredPeople = people.filter(person => Object
.values(person)
.map(String)
.some(v => v.includes('56'))
)
console.log(filteredPeople);
What if I want to return all people with '56' in any property?
You need an array with all such properties with which you want to filter the input array.
var prop = [ "age", "size" ];
Now simply applies the filter in a loop
var valueToMatch = "56";
result = people;
prop.forEach( function( key ){
if ( result.length ) { return true; } //if the result is already empty
result = result.filter( function( peopleObj ){
peopleObj[ key ] == valueToMatch;
});
});
result is the output array filtered with all the properties given in prop array.
Stop using lodash for everything.
JavaScript:
let filtered = people.filter((e) => e.name === ‘foo’ && e.age === 23);
Keep in mind that && forces the two conditions and || says that only one of them must be true.
Extended solution for any number of properties:
var people = [
{ "name":"pete22", "age":56 }, {"name":"sonya56", "age":22 },
{ "name":"john33", "age":33 }, {name: "mike", "login":"56mike", "code": 10 }
],
result = people.filter(function(o){
return Object.keys(o).some(function(k){ return String(o[k]).indexOf("56") !== -1; });
});
console.log(result);
We can filter again with values of Object
people.filter(
hm=>Object.values(hm).filter(
vl=>(vl+'').indexOf(56)>-1).length>0)

Categories

Resources