用nodejs从主json对象中移除嵌套json对象



嗨,我有一个这样的Json对象

"clips"[
{             
"layers": [
{
"type": "image-overlay",
"path": "http://google.com",
},
{
"type": "slide-in-text",
"text": "Some Bags"
},

]
},
{
"duration": 3,
"layers": [
{
"type": "image",
"path": "http://google.com",
"resizeMode": "stretch",
"start": 0,
"stop": 3,
},
{
"type": "image-overlay",
"path": "***vendor**logo*0",
"zoomDirection": "in",
"width": 0.7,
}
]
}
]

我想删除包含

的json对象

***供应商**标志*0

所以我只想删除这个对象:

{
"type": "image-overlay",
"path": "***vendor**logo*0",
"zoomDirection": "in",
"width": 0.7,
}

我的代码是这样的:

jsonObj.clips.map((clip, index)=>{
clip.layers.map((layer, index=>{
if(layer.path === '***vendor**logo*0'){
//Remove layer
}
})
})

我如何用nodejs做到这一点?请帮助!

您可以返回所有其他项,除了您不想要的项

const json = /* your json array */
const newJson = json.map(node => node.layers.filter(layer => layer.path !== "***vendor**logo*0"));

你的问题不是很清楚,所以我不得不猜测一点。但是这里有一个使用object-scan

的潜在解决方案目前,它只适用于数组,但它可以很容易地被推广。如果您有任何问题,请告诉我。

.as-console-wrapper {max-height: 100% !important; top: 0}
<script type="module">
import objectScan from 'https://cdn.jsdelivr.net/npm/object-scan@18.1.2/lib/index.min.js';
const input = { clips: [{ layers: [{ type: 'image-overlay', path: 'http://google.com' }, { type: 'slide-in-text', text: 'Some Bags' }] }, { duration: 3, layers: [{ type: 'image', path: 'http://google.com', resizeMode: 'stretch', start: 0, stop: 3 }, { type: 'image-overlay', path: '***vendor**logo*0', zoomDirection: 'in', width: 0.7 }] }] };
const rm = (obj, v) => objectScan(['**[*].*'], {
abort: true,
rtn: 'bool',
filterFn: ({ gparent, gproperty, value }) => {
if (value === v) {
gparent.splice(gproperty, 1);
return true;
}
return false;
}
})(obj);
console.log(rm(input, '***vendor**logo*0'));
// => true
console.log(input);
// => { clips: [ { layers: [ { type: 'image-overlay', path: 'http://google.com' }, { type: 'slide-in-text', text: 'Some Bags' } ] }, { duration: 3, layers: [ { type: 'image', path: 'http://google.com', resizeMode: 'stretch', start: 0, stop: 3 } ] } ] }
</script>

免责声明:我是object-scan的作者

最新更新