当前位置:网站首页>js中通过key查找和更新对象中指定值的方法
js中通过key查找和更新对象中指定值的方法
2022-06-24 06:59:00 【前端三脚猫】
前言
在js中对象类型的数据取值大多使用obj.a.b.c.d…这种方式取值,但是有时候数据的层级嵌套的非常深每次取值就会非常不方便,所以简单封装两个取值和更新值的小方法。
1、通过key获取对象中的指定值
/**
* 通过key获取对象指定值
* @param {*} obj 取值的对象
* @param {*} objKey 拼接后的key数据,string ‘>’符号拼接
* @return {*} 返回查找到的值
*/
const getObjDataByKey = (obj, objKey) => {
const keyList = objKey.split('>');
return keyList.reduce((pre, item) => pre[item], obj);
}
const data = {
a: {
b: {
c: {
d: [1,2,3]
}
}
}
}
console.log(getObjDataByKey(data, 'a>b>c>d'));
上述代码传入两个参数 (原始数据和通过>拼接的key值),然后通过截取>获取key的list数据,最后通过keyList的reduce方法每次获取一层obj中的数据,直至最后获取最后指定的值返回。打印效果如下:
2、通过key更新obj中的指定数据
/**
* 通过key更新obj中的指定数据
* @param {*} obj 更新值的对象
* @param {*} objKey 拼接后的key数据,string ‘>’符号拼接
* @param {*} newValue 更新的值
* @return {*} 返回更新后的数据
*/
const updateObjDataByKey = (obj, objKey, newValue) => {
const keyList = objKey.split('>');
const lasteKey = keyList[keyList.length - 1];
keyList.reduce((pre, item) => {
if (item === lasteKey) pre[item] = newValue;
return pre[item];
}, obj);
return obj;
}
const data = {
a: {
b: {
c: {
d: [1,2,3]
}
}
}
}
console.log(updateObjDataByKey(data, 'a>b>c>d', [555555555555]));
上述代码传入三个参数 (原始数据、通过>拼接的key值、最新的值),首先通过截取>获取key的list数据,最后通过keyList的reduce方法每次获取一层obj中的数据,判断当循环到keyList最后一级时将newValue赋值给当前数据,最后返回传入的对象即可(中间的赋值利用了引用数据类型的特点)。打印效果如下:
边栏推荐
- RCNN、Fast-RCNN、Faster-RCNN介绍
- io模型初探
- Blue screen error UNMOUNTABLE boot volume of the solution
- 根据网络上的视频的m3u8文件通过ffmpeg进行合成视频
- 2022茶艺师(中级)上岗证题库及在线模拟考试
- ZUCC_编译语言原理与编译_大作业
- 5分钟,客服聊天处理技巧,炉火纯青
- The article takes you to understand the security of Windows operating system and protect your computer from infringement
- ZUCC_编译语言原理与编译_实验04 语言与文法
- Maya re deployment
猜你喜欢
JUC personal simple notes
2022年制冷与空调设备运行操作上岗证题库及模拟考试
ZUCC_编译语言原理与编译_实验05 正则表达式、有限自动机、词法分析
Introduction to RCNN, fast RCNN and fast RCNN
5 minutes, excellent customer service chat handling skills
Swift extension chainlayout (UI chain layout) (source code)
longhorn安装与使用
2021-03-16 COMP9021第九节课笔记
How to use the virtual clock of FPGA?
Longhorn installation and use
随机推荐
PAT 1157:校庆
pyQt 中 QMenu 响应
jwt(json web token)
Cloudbase database migration scheme
The article takes you to understand the security of Windows operating system and protect your computer from infringement
LabVIEW finds prime numbers in an array of n elements
2021-03-04 COMP9021第六节课笔记
新准则金融资产三分类:AMC、FVOCI和FVTPL
longhorn安装与使用
Three ways to uninstall Symantec Endpoint Protection Symantec
For a detailed explanation of flex:1, flex:1
Easydss anonymous live channel data volume instability optimization scheme sharing
Longhorn installation and use
一文带你了解Windows操作系统安全,保护自己的电脑不受侵害
Use cpulimit to free up your CPU
Pat 1157: school anniversary
After interviewing and tutoring several children, I found some problems!
The JS macro of WPS implements the separation method of picture text in the same paragraph
将mysql的数据库导出xxx.sql,将xxx.sql文件导入到服务器的mysql中。项目部署。
MAYA重新拓布