如何从文字对象数组中删除元素

时间:2018-10-29 18:06:58

标签: javascript

您好,我正在尝试从数组数据内的每个对象中删除actions属性:

[{productName: "", ... action: ...,}, {productName: "", ...action:...} ...]

6 个答案:

答案 0 :(得分:2)

var arr  =[{productName: "bbbb", action: 'b'},
         {productName: "aa",action: 'a'}, 
         {productName: "tt",action: 't'}, 
         {productName: "vv",action: 'v'}]


arr = arr.map((d) => {delete d.action ; return d;});

答案 1 :(得分:1)

1)使用map(...)

your_array.map(o => {'productName': o.productName})

请注意,如果您要过滤掉许多属性,这样做会更优雅,但是如果您只想删除一个属性,则需要做更多的工作。

2)使用delete

for (let i = 0; i < your_array.length; i++){
    delete your_array[i].action
}

答案 2 :(得分:1)

使用mapdestructure对象遍历数组以仅保留必填字段

var arr = [{
  producet: 'xyz',
  action: 'abc',
  other: 'o'
}, {
  producet: 'xyz',
  action: '123',
  other: 'o'
}, {
  producet: 'xyz',
  action: 'sdf',
  other: 'o'
}]
const result = arr.map(({
  action,
  ...rest
}) => rest);
console.log(result);

答案 3 :(得分:1)

使用ES6,您可以将mapdestructuringrest parameters结合使用,以分离出要保留的对象属性和要丢弃的部分:

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>title</title>
        <link rel="stylesheet" href="/css/style.css">
    </head>
    <body>
    <c:choose>
        <c:when test="${error}">
            Erro.
            <br />
        </c:when>
        <c:otherwise>
            <c:out value="${sessionScope.login}"/> | <a href="<c:url value = "/logout"/>">Sair</a>.
            <br />
        </c:otherwise>
    </c:choose>
    <script src="/js/script.js"></script>
    </body>
</html>

答案 4 :(得分:0)

使用数组map将返回一个新数组。在map回调中创建一个新对象,并仅填充那些必填字段。不要更改原始数组

var arr = [{
  productName: "1",
  action: ''
}, {
  productName: "2",
  action: ''
}];


let newArr = arr.map(function(item) {
  return Object.assign({}, {
    productName: item.productName
  })
});
console.log(newArr)

答案 5 :(得分:0)

根据docs,您可以使用delete运算符。

执行此操作的一种简单方法是遍历数组arr并从每个对象中删除属性。

for (var i = 0; i < arr.length; i++){
    delete arr[i].action;
}

此方法is slightly faster比其他方法,例如mapfor each