Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

JavaScript 데이터를 가공해보자 (Data Processing in JavaScript)

JAVASCRIPT, 20215 min read

배경

react로 코드를 쓸 때 api에서 호출받은 결과를 가공하는 일이 많다고 느꼈다 간단한 예시와 MDN에서 찾은 내용을 정리하려고 한다.

Convert Array to Object

const array = [ '1','2']
array.reduce(function(target, key, index) {
target[index] = key;
return target;
}, {}) // { 0: "1", 1 : "2" }
const arr = ["q"];
const obj = {...arr};
console.log(obj); //{0:"q"}

Convert Object to Array

const obj = {"a" : 1, "b" : 2};
const arr = Object.keys(obj).map(function (key) {
return [String(key), obj[key]];
});
console.log(arr); // [ [ 'a', 1 ], [ 'b', 2 ] ]
const obj = {"a" : 1, "b" : 2};
const arr = Object.entries(obj);
console.log(arr); // [ [ 'a', 1 ], [ 'b', 2 ] ]

How can I add a key/value pair to a JavaScript object

var obj = {
key1: value1,
key2: value2
};
obj.key3 = "value3";
obj["key4"] = "value4";
var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key5");

how to know value in array

const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true

how to make array unique

const unique = (value, index, self) => {
return self.indexOf(value) === index
}
const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = ages.filter(unique)
console.log(uniqueAges)

how to push item to Array in javascript

const array = [1];
array.push(2);

how to get value in Array

const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"

find an item in an object javascript

const object1 = {
a: {val: "aa"},
b: {val: "bb"},
c: {val: "cc"}
};
let a = Object.values(object1).find((obj) => {
return obj.val == "bb"
});
console.log(a)//Object { val: "bb" }

How to get a key in a JavaScript object by its value

function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const map = {"first" : "1", "second" : "2"};
console.log(getKeyByValue(map,"2"));

map filter

const unique = (value, index, self) => {
return self.indexOf(value) === index
}
const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = ages.filter(unique)
console.log(uniqueAges)

Use .map without return in simple way

const members = [
{ num: 1, name:'te' },
{ num: 2, name:'te2' }
];
const list = members.map(elem => (
{
num: elem.num + 1 ,
name: elem.name
}
));
console.log(list);
/*[
{ num: 2, name:'te' },
{ num: 3, name:'te2' }
]*/

javascript sort array of objects by property

const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]
var sortedArray = list.sort((a, b) => (a.color > b.color) ? 1 : -1)
// Result:
//sortedArray:
//{ color: 'black', size: 'M' }
//{ color: 'red', size: 'XL' }
//{ color: 'white', size: 'XXL' }
var array = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "Jake", age: 25}
];
array.sort(function(a, b) {
return a.age - b.age;
}); // Sort youngest first

sort

const array1 = [1, 30, 4, 21, 100000];
array1.sort();

sort-1

const sorted = [...dogList].sort((a, b) => {
return b.age - a.age;
});

Better way to sum a property value in an array

var traveler = [{description: 'Senior', Amount: 50},
{description: 'Senior', Amount: 50},
{description: 'Adult', Amount: 75},
{description: 'Child', Amount: 35},
{description: 'Infant', Amount: 25}];
function amount(item){
return item.Amount;
}
function sum(prev, next){
return prev + next;
}
traveler.map(amount).reduce(sum);
// => 235;
// or use arrow functions
traveler.map(item => item.Amount).reduce((prev, next) => prev + next);

reduce

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10

JSON 형태

  • JSON은 JavaScript Object Notation의 약자로, 브라우저와 서버사이에서 오고가는 데이터의 형식
  • JavaScript 값이나 객체를 JSON 문자열로 변환
  • 문자열을 감쌀 때 쌍따옴표("")를 사용

JSON.parse

const json = `{"result":true, "count":42 , "text":"문자입력"}`;
const obj = JSON.parse(json);
console.log(obj.text);

JSON 문자열의 구문을 분석하고 Json 객체 생성 주의 key 값은 "" 추가, value 가 string 이라면 "" 추가 변환하려는 string 의 형태가 틀리면 is not valid JSON 이라는 에러 발생

JSON.stringify

console.log(JSON.stringify({ num: 5,text : "s",
bool:new Boolean('false') ,
boolStr :new String('false') ,
date : new Date(2006, 0, 2, 15, 4, 5)
}));
//'{"num":5,"text":"s","bool":true,"boolStr":"false","date":"2006-01-02T06:04:05.000Z"}'

Check if Multiple Values exist in an Array in JavaScript

배경 역할에 code 값을 추가하고 a,b 2개의 code 값이 모두 존재하는 경우 true 를 반환하는 코드가 필요했다.

const multipleInArray = (arr, values) => {
return values.every(value => {
return arr.includes(value);
})
}
//[1, 2, 3] 에 [1,3] 의 값이 모두 있니?
// console.log(multipleInArray([1, 2, 3], [1, 3])); true

serialize

객체 직혈화는 객체를 문자열로 변화하는 작업

JSON

데이터 교환 형식인 자바스크립트 객체 표기법

  • JSON.stringify()

  • JSON.parse()

참고

https://steemit.com/kr-dev/@cheonmr/json-stringify

compare two array (JSON.stringify)

const a = [a, b, c];
const b = [a, b, d];
const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b);
equals(a, b); // false

https://sisiblog.tistory.com/258

Array.prototype.some (Array some)

const hsaNumber= (num) => [
1,2,3,4,5
].some(item => item === num);
hsaNumber(4); //true
hsaNumber(50); //false
© 2024 by GwiyeomGo Tech Blog. All rights reserved.