Advertisements
I have an array object in a variable called maintemp.
const maintemp = [
[
{
equipId: 1,
name: '1메인 온도 센서',
sensors: [
{
tagId: 11,
name: '온도',
value: 28.8,
tagClass: {
bitCalcYn: 'N',
code: 'INNERTEMP',
encoding: 'ONEDECIMALPOINT',
isDigital: 'N',
},
},
],
},
{
equipId: 2,
name: '1메인 습도 센서',
sensors: [
{
tagId: 22,
name: '습도',
value: 50.3,
tagClass: {
bitCalcYn: 'N',
code: 'INNERAHUM',
encoding: 'ONEDECIMALPOINT',
isDigital: 'N',
name: '실내 습도',
},
},
],
},
],
[
{
equipId: 3,
name: '2메인 온도 센서',
sensors: [
{
tagId: 11,
name: '온도',
value: 28.8,
tagClass: {
bitCalcYn: 'N',
code: 'INNERTEMP',
encoding: 'ONEDECIMALPOINT',
isDigital: 'N',
},
},
],
},
{
equipId: 4,
name: '2메인 습도 센서',
sensors: [
{
tagId: 22,
name: '습도',
value: 50.3,
tagClass: {
bitCalcYn: 'N',
code: 'INNERAHUM',
encoding: 'ONEDECIMALPOINT',
isDigital: 'N',
name: '실내 습도',
},
},
],
},
],
];
At this time, I want to put only the object whose tagClass.code is ‘INNERTEMP’ into the variable fill by using the map function and the filter function.
However, when I run my code, the entire array is not filtered and the entire array is stored in the fill variable. How do I fix the code?
this is my code
const fill = maintemp.filter((v) =>
v.filter((hi) => hi.sensors[0].tagClass.code === "INNERTEMP'")
);
expected answer
const fill = [
{
equipId: 1,
name: '1메인 온도 센서',
sensors: [
{
tagId: 11,
name: '온도',
value: 28.8,
tagClass: {
bitCalcYn: 'N',
code: 'INNERTEMP',
encoding: 'ONEDECIMALPOINT',
isDigital: 'N',
},
},
],
},
{
equipId: 3,
name: '2메인 온도 센서',
sensors: [
{
tagId: 11,
name: '온도',
value: 28.8,
tagClass: {
bitCalcYn: 'N',
code: 'INNERTEMP',
encoding: 'ONEDECIMALPOINT',
isDigital: 'N',
},
},
],
},
]
>Solution :
You can first flatten your array then filter items:
fill = maintemp.flat().filter((hi) => hi.sensors[0].tagClass.code === "INNERTEMP")
const maintemp = [[{"equipId":1,"name":"1메인 온도 센서","sensors":[{"tagId":11,"name":"온도","value":28.8,"tagClass":{"bitCalcYn":"N","code":"INNERTEMP","encoding":"ONEDECIMALPOINT","isDigital":"N"}}]},{"equipId":2,"name":"1메인 습도 센서","sensors":[{"tagId":22,"name":"습도","value":50.3,"tagClass":{"bitCalcYn":"N","code":"INNERAHUM","encoding":"ONEDECIMALPOINT","isDigital":"N","name":"실내 습도"}}]}],[{"equipId":3,"name":"2메인 온도 센서","sensors":[{"tagId":11,"name":"온도","value":28.8,"tagClass":{"bitCalcYn":"N","code":"INNERTEMP","encoding":"ONEDECIMALPOINT","isDigital":"N"}}]},{"equipId":4,"name":"2메인 습도 센서","sensors":[{"tagId":22,"name":"습도","value":50.3,"tagClass":{"bitCalcYn":"N","code":"INNERAHUM","encoding":"ONEDECIMALPOINT","isDigital":"N","name":"실내 습도"}}]}]];
const fill = maintemp.flat().filter((hi) => hi.sensors[0].tagClass.code === "INNERTEMP")
console.log(fill)
.as-console-wrapper { max-height: 100% !important; }